MSAL Angular - 通过 document.location.origin 进行动态重定向 Url 配置不适用于 AOT

ak.*_*rey 2 azure-ad-msal angular msal.js

我正在编写一个 Angular 应用程序,同时尽力避免根据环境变量重建我的项目。对于基本的后端 API 调用,分别使用document.location.origin和/或非常容易window.location.origin。引用托德·霍华德最臭名昭著的一句话:“它就是有效”。我必须承认,到目前为止,我的应用程序需要解决相当简单的问题,因此我缺乏一些中间概念的知识。然而,最终客户希望使用 MSAL 库将其用作备用 Active Directory,并为了方便“单点登录策略”。我忽略了在生产性构建中尝试它,意识到我不能像这样使用它......

 MsalModule.forRoot({
      auth: {
        clientId: '<my_client_id>',
        authority: '',
        redirectUri: window.location.origin,
        postLogoutRedirectUri: window.location.origin + "/login"
      },
      cache: {
        cacheLocation: 'localStorage',
        storeAuthStateInCookie: isIE, // set to true for IE 11
      },
    },
Run Code Online (Sandbox Code Playgroud)

我还没有看到太多类似案例的应用解决方案。我发现这个特定问题的唯一原因是通过这个 git-issue 帖子

https://github.com/angular/angular-cli/issues/10957

我的问题是,有没有办法为 AOT 构建提供窗口对象?

ak.*_*rey 6

因此,在四处挖掘并考虑到人们的沉默之后......我通过挖掘 MSAL 库的 Git 找到了解决方案。

const isIE = window.navigator.userAgent.indexOf('MSIE ') > -1 || window.navigator.userAgent.indexOf('Trident/') > -1;


export const protectedResourceMap: [string, string[]][] = [
  ['https://graph.microsoft.com/v1.0/me', ['user.read']]
];

// This setup won't change in our environment, so we were fine with having it statically included
export const clientId = window.location.origin.includes('qa') || window.location.origin.includes('localhost') ? '<qa_id>' : '<prod_id>';

export function MSALConfigFactory(): Configuration {
  return {
    auth: {
      clientId,
      authority: "https://login.microsoftonline.com/common/",
      validateAuthority: true,
      redirectUri: window.location.origin,
      postLogoutRedirectUri: window.location.origin,
      navigateToLoginRequestUrl: true,
    },
    cache: {
      cacheLocation: "localStorage",
      storeAuthStateInCookie: isIE, // set to true for IE 11
    },
  };
}

export function MSALAngularConfigFactory(): MsalAngularConfiguration {
  return {
    popUp: !isIE,
    consentScopes: [
      "user.read",
      "openid",
      "profile"
    ],
    unprotectedResources: [],
    protectedResourceMap,
    extraQueryParameters: {}
  };
}
Run Code Online (Sandbox Code Playgroud)

我们没有使用MsalModule.forRoot({},{})无法通过窗口进行动态设置的配置,而是仅MsalModule在app.module.ts. 所以而不是...

imports: [
.. // shortened for terseness
MsalModule.forRoot({},{}),
..
]
Run Code Online (Sandbox Code Playgroud)

我们确实将其更改为...

imports: [
.. // shortened for terseness
MsalModule,
..
]
Run Code Online (Sandbox Code Playgroud)

对于提供者,我们需要提供MSAL_CONFIG类,但我们还需要提供我们想要使用的配置,这是我们之前所做的。不要忘记包含 MsalService,否则应用程序将无法运行。

  providers: [
    {
      provide: MSAL_CONFIG,
      useFactory: MSALConfigFactory
    },
    {
      provide: MSAL_CONFIG_ANGULAR,
      useFactory: MSALAngularConfigFactory
    },
    MsalService,
  ],
Run Code Online (Sandbox Code Playgroud)

该应用程序已在Angular 7项目上进行了测试,即使使用高效构建 + AOT 也能按预期工作