我的解决方案是编写自己的自定义守卫,从 Microsoft 的 github 复制守卫的代码:https ://github.com/AzureAD/microsoft-authentication-library-for-js/blob/dev/lib/msal-angular/ src/msal.guard.ts
然后我调整了我复制的课程,首先通过注入语言,我为此提供了语言服务:
export class MsalLocaleGuard
implements CanActivate, CanActivateChild, CanLoad {
private loginFailedRoute?: UrlTree;
protected subsink = new SubSink();
currentLanguage: string | undefined;
constructor(
@Inject(MSAL_GUARD_CONFIG) private msalGuardConfig: MsalGuardConfiguration,
private msalBroadcastService: MsalBroadcastService,
private authService: MsalService,
private location: Location,
private router: Router,
private languageService: LanguageService
) {
super();
// Subscribing so events in MsalGuard will set inProgress$ observable
this.msalBroadcastService.inProgress$.subscribe();
if (this.languageService.currentName) {
this.subsink.sink = this.languageService.currentName.subscribe(
(lang) => (this.currentLanguage = lang)
);
}
}
然后我不得不更改方法 loginInteractively 以将当前语言作为 ui-locales 属性传递。这是我添加的行:extraQueryParameters: { ui_locales: this.currentLanguage },
整个方法如下所示:
/**
* Interactively prompt the user to login
* @param url Path of the requested page
*/
private loginInteractively(state: RouterStateSnapshot): Observable<boolean> {
// const authRequest = typeof this.msalGuardConfig.authRequest === "function"
// ? this.msalGuardConfig.authRequest(this.authService, state)
// : { ...this.msalGuardConfig.authRequest };
if (this.msalGuardConfig.interactionType === InteractionType.Popup) {
this.authService.getLogger().verbose('Guard - logging in by popup');
return this.authService
.loginPopup(this.msalGuardConfig.authRequest as PopupRequest)
.pipe(
map((response: AuthenticationResult) => {
this.authService
.getLogger()
.verbose(
'Guard - login by popup successful, can activate, setting active account'
);
this.authService.instance.setActiveAccount(response.account);
return true;
})
);
}
this.authService.getLogger().verbose('Guard - logging in by redirect');
const redirectStartPage = this.getDestinationUrl(state.url);
return this.authService
.loginRedirect({
redirectStartPage,
//...authRequest,
...this.msalGuardConfig.authRequest,
extraQueryParameters: { ui_locales: this.currentLanguage },
} as RedirectRequest)
.pipe(map(() => false));
}
然后我在 app.module 的提供程序部分使用了这个新的 MsalLocaleGuard。
这不是一个最佳解决方案,因为当微软更新他们的代码时,我的代码从 github 复制的代码就会过时。但这是一种解决方法,在有更好的方法之前就足够了。