多租户

默认情况下,你的应用程序支持多租户,因为如果配置中未指定租户,MSAL 会将颁发机构中的租户设置为“common”。这使得任何 Microsoft 帐户都能对你的应用程序进行身份验证。 如果你不需要多租户行为,则需要在 app.module.ts 中实例化 MSAL 时设置 authority 配置属性,如下所示。

@NgModule({
  imports: [
    MsalModule.forRoot({ // MSAL Configuration
      auth: {
        clientId: 'CLIENT_ID_HERE',
        authority: 'https://login.microsoftonline.com/TENANT_ID_HERE',
        redirectUri: 'http://localhost:4200',
        postLogoutRedirectUri: 'http://localhost:4200'
      },
      // Additional configuration here
    });
  ]
})
export class AppModule {}

如果允许多租户身份验证,但又不希望所有 Microsoft 帐户用户都能使用你的应用程序,则必须提供自己的筛选方法,将令牌签发者限定为仅允许登录的那些租户。

更改租户

还可以通过在相关组件中实例化 MSAL 的新实例来动态设置租户,如下所示。

import { PublicClientApplication } from '@azure/msal-browser';
import { MsalService } from '@azure/msal-angular';

@Component({})
export class AppComponent implements OnInit {
  constructor(
    private authService: MsalService
  ) {}

  ngOnInit(): void {
    this.authService.instance = new PublicClientApplication({
      auth: {
        clientId: 'CLIENT_ID_HERE',
        authority: 'https://login.microsoftonline.com/TENANT_ID_HERE',
        redirectUri: 'http://localhost:4200',
        postLogoutRedirectUri: 'http://localhost:4200'
      }
    });
  }

动态身份验证请求

默认情况下,MsalGuard 和 MsalInterceptor 使用配置中设置的静态属性。还可以使用方法 authRequest配置这两种方法,从而允许动态更改用于身份验证的参数。

MsalInterceptor - 动态身份验证请求(多租户令牌)

如果将 organizationscommon 用作租户,则将为用户的主租户请求所有令牌。 但是,这可能不是所需的结果。 如果用户被邀请为来宾,令牌可能来自错误的颁发机构。

MsalInterceptorConfig 中的 authRequest 设置为一个方法,可让你动态更改身份验证请求。 例如,在使用来宾用户时,可以基于帐户的主租户设置颁发机构。 authRequest 上的属性可以更改,但应始终继承自 originalAuthRequest,如下面所示:

export function MSALInterceptorConfigFactory(): MsalInterceptorConfiguration {
  const protectedResourceMap = new Map<string, Array<string>>();
  protectedResourceMap.set("https://graph.microsoft.com/v1.0/me", ["user.read"]);
  
  return {
    interactionType: InteractionType.Popup,
    protectedResourceMap,
    authRequest: (msalService, httpReq, originalAuthRequest) => {
      return {
        ...originalAuthRequest,
        authority: `https://login.microsoftonline.com/${originalAuthRequest.account?.tenantId ?? 'organizations'}`
      };
    }
  };
}
...

@NgModule({
  declarations: [...],
  imports: [...],
  providers: [
    ...
    {
      provide: MSAL_INTERCEPTOR_CONFIG,
      useFactory: MSALInterceptorConfigFactory
    }
  ]
});