ADAL/MSAL JS库与Angular 2+一起使用以及处理iFrames

3
I'm working on an Angular (7.0) SPA application and would like to implement Azure AD login for authentication and authorization functionality. The app consumes a .NET Core 2.1 API.
Currently, the Angular app consists of three components - home, login, and redirect.
The home component is protected by a Route Guard, so if the user is not logged in, they will be redirected to the login component. The login component checks if the user is authenticated. If not, they are redirected to the Microsoft login page. If the login is successful, the user is directed to the Redirect component, which then sends them to the default page, the home page.
Up until this point, everything works fine without any issues. However, problems arise when attempting to acquire an access token for the .NET Core API.
The adal-angular4 library is used.
//HTTP Interceptor
this.adal.acquireToken(resource) ...

@azure/msal-angular

//HTTP Interceptor
this.msal.acquireTokenSilent(scopes) ...

当我获取令牌并且HTTP拦截器附加令牌时,这些函数被执行时,它们会创建一个新的应用实例,没有任何问题。
<html>
<head>...</head>
<body>
<app-root>...</app-root>
<script type="text/javascript" src="runtime.js"></script>
<script type="text/javascript" src="polyfills.js"></script>
<script type="text/javascript" src="styles.js"></script>
<script type="text/javascript" src="vendor.js"></script>
<script type="text/javascript" src="main.js"></script>
<iframe id="msalRenewFramehttps://address.net/.../..." src="https://login.microsoftonline.com/...">
    <html>
    <head>...</head>
    <body>
    <app-root>...</app-root>
    <script type="text/javascript" src="runtime.js"></script>
    <script type="text/javascript" src="polyfills.js"></script>
    <script type="text/javascript" src="styles.js"></script>
    <script type="text/javascript" src="vendor.js"></script>
    <script type="text/javascript" src="main.js"></script>
    </body>
    </html>
</iframe>
</body>
</html>

这意味着,如果我在主页上有一些后台运行的任务,在构造函数中启动,两个实例都会开始运行这些任务并访问服务器。
关于ADAL.JS,有两种建议来解决此问题,但没有一种适用于Angular 2+。
其中一个可能的解决方案是每次获取/更新令牌时从HTML中删除iframe,但这似乎是一个相当糟糕的解决方案。
我100%确定Azure Portal和Angular应用程序上的重定向地址是正确的。
过去一周一直在努力解决这个问题。非常感谢任何帮助。

你是否已经找到了这个问题的解决方案? - Nico
1个回答

0

我花了太多时间调查这个问题。 @azure/msal-angular 还没有准备好,使用旧版本的 msal 会导致很多问题。因此,我们决定直接使用 msal 并自己实现守卫和 HTTP 拦截器。

通过转向 msal,我们能够将登录后重定向页面提取到自己的 HTML 文件中,如下所示:

<script type="text/javascript" src="https://alcdn.msauth.net/lib/1.2.1/js/msal.js"
  integrity="sha384-9TV1245fz+BaI+VvCjMYL0YDMElLBwNS84v3mY57pXNOt6xcUYch2QLImaTahcOP" crossorigin="anonymous"></script>
<script>
  new Msal.UserAgentApplication({ auth: config })
    .handleRedirectCallback((err, res) => {
      if (err) {
        console.error(err);
        return;
      }
    });
</script>

之后,由于在 iframe 中重复应用程序,我们再也没有遇到捆绑包重新加载的情况。此外,认证流程更快了。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接