簡體   English   中英

如何在 Angular 中基於 Request Uri 在自定義攔截器和 Msal 攔截器之間使用條件攔截器

[英]How to use conditional interceptor between custom Interceptor and Msal Interceptor based on Request Uri in Angular

我在我的 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)
        )
    );
}

任何幫助表示贊賞。 提前致謝。

想出了一個臨時的解決方案。 剛剛將 MSALInterceptor 移到 AuthInterceptor 上方。 不知道它是否是一個好的解決方案,但不知何故這有效。

{
  provide: HTTP_INTERCEPTORS,
  useClass: MsalInterceptor,
  multi: true
},
{
  provide: HTTP_INTERCEPTORS,
  useClass: AuthInterceptor,
  multi: true
},

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM