передать ui_locales в Msal Angular Guard

Я использую Msal Guard в своем приложении Angular.

В моем проекте тоже есть локализация. Я знаю, что могу использовать extraQueryParameters { ui_locales: 'de' } в моем RedirectRequest объект, который я затем могу передать msalAuthService.loginRedirect метод.

Но msalGuard автоматически выполняет перенаправление входа, когда пользователь пытается перейти на защищенную страницу. Интересно, есть ли способ каким-то образом передать ui_locales в msalGuard? Или мне нужно написать для этого свой собственный охранник.

1 ответ

Мое решение заключалось в том, чтобы написать свой собственный охранник, копирующий код для охранника из github от Microsoft: 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));
}

Затем я использовал этот новый MsalLocaleGuard в разделе поставщиков моего app.module.

Это не оптимальное решение, потому что, когда Microsoft обновляет код в своей защите, код в моей защите, скопированный с github, устаревает. Но это обходной путь, которого достаточно, пока не будет лучшего способа.

Другие вопросы по тегам