前言
因為項目需求,需要把Angular 11項目中登錄方式改成B2C登錄,所以在參考了一系列文檔后,成功通過MSAL將項目的登錄方式改成B2C登錄。下面介紹了詳細步驟及一些注意事項。
步驟:
1. 安裝MSAL
在項目中安裝msal
npm i @azure/msal-angular --save
npm i @azure/msal-browser --save
通過查閱MSAL的文檔,發現v2以上版本才支持Angualr11,所以在本項目的代碼中使用的是:
"@azure/msal-angular": "^2.0.3",
"@azure/msal-browser": "^2.17.0",
2. 引入MSAL
在項目中引入MSAL主要是在兩個文件中引入,app.module.ts和app-routing.module.ts中引入,下面先講解app.module.ts這個文件。
app.module.ts
...
import { IPublicClientApplication, PublicClientApplication, InteractionType, BrowserCacheLocation, LogLevel } from '@azure/msal-browser';
import { MsalInterceptor, MsalBroadcastService, MsalInterceptorConfiguration, MsalModule, MsalService, MSAL_INSTANCE, MSAL_INTERCEPTOR_CONFIG, MsalRedirectComponent } from '@azure/msal-angular';export function loggerCallback(logLevel: LogLevel, message: string) {
}export function MSALInstanceFactory(): IPublicClientApplication {return new PublicClientApplication({auth: {clientId: "your-client-id",authority: "your-authority",knownAuthorities: "your-knownAuthorities", redirectUri: "your-redirectUri", postLogoutRedirectUri: "your-LogoutRedirectUri:"}cache: {cacheLocation: BrowserCacheLocation.SessionStorage,storeAuthStateInCookie: false, },system: {loggerOptions: {loggerCallback,logLevel: LogLevel.Info,piiLoggingEnabled: false}}});
}export function MSALInterceptorConfigFactory(): MsalInterceptorConfiguration {const protectedResourceMap = new Map<string, Array<string>>();protectedResourceMap.set("your-local-set", [yourB2CScope]);return {interactionType: InteractionType.Redirect,protectedResourceMap};
}@NgModule({declarations: [...],imports: [...MsalModule],providers: [...{provide: HTTP_INTERCEPTORS,useClass: MsalInterceptor,multi: true},{provide: MSAL_INSTANCE,useFactory: MSALInstanceFactory},{provide: MSAL_INTERCEPTOR_CONFIG,useFactory: MSALInterceptorConfigFactory},MsalService,MsalBroadcastService],bootstrap: [AppComponent, MsalRedirectComponent]
})
}
注意: 在以上實例中,your開頭的,都是需要自己配置的信息。 省略號代表著你自己項目中的其他代碼。
#app-routing.module.ts會在下篇文章講解