我已经在我的 angular 11 项目中实现了 @azure/msal-angular 2.0。 我在这个项目中使用了 2 个 API。 很少有 API 需要自定义拦截器 (AuthInterceptor),也很少需要 msal.js 的 MsalInterceptor。 两个 API 一次只能使用一个拦截器,否则请求将失败。 我想知道如何在单个拦截器中自定义 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)
)
);
}
感谢任何帮助。提前致谢。
答案 0 :(得分:0)
想出了一个临时解决方案。刚刚将 MSALInterceptor 移到 AuthInterceptor 之上。 不知道它是否是一个好的解决方案,但不知何故这奏效了。
{
provide: HTTP_INTERCEPTORS,
useClass: MsalInterceptor,
multi: true
},
{
provide: HTTP_INTERCEPTORS,
useClass: AuthInterceptor,
multi: true
},