我已经在我的angular 11项目中实现了@azure/msal-angular 2.0。我已经在这个项目中使用了2个Apis。很少有APis需要自定义拦截器(AuthInterceptor),也很少需要MsalInterceptor by msal.js。两个API一次只能使用一个Interceptor,否则请求将失败。我想知道如何在一个拦截器中定制MsalInterceptor和CustomInterceptor。
这是我的app.module.ts文件(在这里,我想删除msalinterceptor并在AuthInterceptor中定制它,或者我想把两个拦截器都保留在这里,并根据请求URI有条件地使用它)
providers: [
{
provide: HTTP_INTERCEPTORS,
useClass: AuthInterceptor,
multi: true
},
{
provide: HTTP_INTERCEPTORS,
useClass: MsalInterceptor,
multi: true
},
{
provide: MSAL_INSTANCE,
useFactory: MSALInstanceFactory
},
{
provide: MSAL_GUARD_CONFIG,
useFactory: MSALGuardConfigFactory
},
{
provide: MSAL_INTERCEPTOR_CONFIG,
useFactory: MSALInterceptorConfigFactory
},
MsalService,
MsalGuard,
MsalBroadcastService
],
这就是我在这个文件中使用MsalInterceptor定制AuthInterceptor的方法。
intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
if (req.url.indexOf(this.APIOne) !== -1) {
// I want to use USE MSALInterceptor Here. but it is not working.
const scopesInformation = {
scopes: [
'mail.send'
],
};
this.auth.instance.acquireTokenSilent(scopesInformation).then(tokenResponse => {
debugger;
req = req.clone({
setHeaders: { Authorization: 'Bearer ' + tokenResponse.accessToken }
});
});
} else
if (req.url.indexOf(this.APITwo) !== -1) {
// This is my custom interceptor which does not require MsalInterceptor Token.
this.token = localStorage.getItem('APITwoToken');
const authReq = req.clone({
headers: new HttpHeaders({
'Cache-Control': 'no-cache, no-store, must-revalidate, post-check=0, pre-check=0',
'Pragma': 'no-cache',
'Expires': 'Sat, 01 Jan 2000 00:00:00 GMT'
}), setHeaders: { Authorization: 'Bearer ' + this.token }
})
req = authReq;
}
return next.handle(req).pipe(
tap(
event => this.handleResponse(req, event),
error => this.handleError(req, error)
)
);
}
任何帮助都是非常感谢的。提前谢谢。
发布于 2021-04-21 19:23:50
想出了一个临时的解决方案。刚把MSALInterceptor移到了AuthInterceptor上面。不知道这是不是一个好的解决方案,但不知何故,这是有效的。
{
provide: HTTP_INTERCEPTORS,
useClass: MsalInterceptor,
multi: true
},
{
provide: HTTP_INTERCEPTORS,
useClass: AuthInterceptor,
multi: true
},
https://stackoverflow.com/questions/67190747
复制相似问题