我在我的 Angular 项目中使用
msal-angular
。我想在重定向到 https://login.microsoftonline.com
之前显示自定义登录页面(一种登陆页面)。我的代码基于官方示例。
我没有用任何防护来保护我的自定义登录页面:
const routes: Routes = [
{
path: '',
component: HomeComponent,
canActivate: [authGuard]
},
{
path: 'login',
component: LoginComponent
}
];
当我未登录时,我可以看到登录页面大约 1 秒,然后我会自动重定向到 MS 登录页面,这是我想要避免的。
当我从 app.module.ts 中的
MsalRedirectComponent
部分删除 bootstrap
时:
bootstrap: [AppComponent, MsalRedirectComponent]
未触发重定向,但是,当单击登录页面中的登录按钮时,出现以下错误:
错误错误:未捕获(承诺):BrowserAuthError: uninitialized_public_client_application:您必须调用并等待 在尝试调用任何其他 MSAL API 之前初始化函数
LoginComponent 中的login():
login(): void {
if (this.msalGuardConfig.authRequest) {
this.authService.loginRedirect({...this.msalGuardConfig.authRequest} as RedirectRequest);
} else {
this.authService.loginRedirect();
}
}
上述错误的解决方案是在初始化组件时添加以下行:
this.authService.initialize().subscribe();
this.authService.handleRedirectObservable().subscribe();
添加它们后,错误消失了,但我再次被自动重定向。有没有办法不自动触发重定向,而是在单击按钮时以编程方式触发重定向?
我能够解决这个问题,所以将分享解决方案。
当向受保护资源发送请求时,MSAL 拦截器会触发重定向或弹出窗口。受保护的资源在
MSALInterceptorConfigFactory
: 中配置
export function MSALInterceptorConfigFactory(): MsalInterceptorConfiguration {
const protectedResourceMap = new Map<string, Array<string>>();
protectedResourceMap.set("/api/*", ["user.read"]);
return {
interactionType: InteractionType.Redirect,
protectedResourceMap,
};
}
在我的例子中,尽管用户尚未登录,但还是发送了请求,这导致了重定向。
我也遵循相同的方法并面临与您所面临的相同问题。您能否给我相同的代码或 git-hub 链接,以便我可以使我的代码工作。 预先感谢。