我在我的Angular应用程序中使用了Msal Guard。
我在我的项目中也有本地化。我知道可以在RedirectRequest对象中使用extraQueryParameters { ui_locales: 'de' },然后将其传递给msalAuthService.loginRedirect方法。
但是,当用户尝试导航到受保护的页面时,msalGuard会自动执行登录重定向。我想知道有没有办法以某种方式将ui_locales传递给msalGuard?或者我需要编写自己的自定义保护才能做到这一点。
发布于 2021-07-01 17:11:20
我的解决方案是编写自己的自定义卫士,从微软的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的providers部分使用了这个新的MsalLocaleGuard。
这不是一个最优的解决方案,因为当微软在他们的守卫中更新代码时,我的守卫中从github复制的代码就会过时。但这是一种变通方法,在找到更好的方法之前就已经足够了。
https://stackoverflow.com/questions/67122269
复制相似问题