如何让 MSAL 拦截器向 Apollo GraphQL 请求添加标头

问题描述 投票:0回答:1

我正在尝试在我的应用程序中设置身份验证,并且我已经尝试了多种资源来解决此问题。

简单地说,MSAL 拦截器似乎没有在应用程序中工作。我需要做什么才能正确?

登录和注销过程工作正常,但是当我对服务器运行查询时出现 500 错误,并且请求标头中没有令牌。主机函数只是返回当前窗口的原点(而不是对主机进行硬编码)

在我的 app.module 中,我有以下内容。

/**
 * Here we pass the configuration parameters to create an MSAL instance.
 * For more info, visit: https://github.com/AzureAD/microsoft-authentication-library-for-js/blob/dev/lib/msal-angular/docs/v2-docs/configuration.md
 */
export function MSALInstanceFactory(): IPublicClientApplication {
  return new PublicClientApplication(msalConfig);
}

/**
* Set your default interaction type for MSALGuard here. If you have any
* additional scopes you want the user to consent upon login, add them here as well.
*/
export function MsalGuardConfigurationFactory(): MsalGuardConfiguration {
  return {
      interactionType: InteractionType.Redirect,
      authRequest: loginRequest
  };
}

/**
* MSAL Angular will automatically retrieve tokens for resources
* added to protectedResourceMap. For more info, visit:
* https://github.com/AzureAD/microsoft-authentication-library-for-js/blob/dev/lib/msal-angular/docs/v2-docs/initialization.md#get-tokens-for-web-api-calls
*/
export function MSALInterceptorConfigFactory(): MsalInterceptorConfiguration {
  const protectedResourceMap = new Map<string, Array<string | ProtectedResourceScopes> | null>();

  protectedResourceMap.set(protectedResources.graphMe.endpoint, protectedResources.graphMe.scopes);
  protectedResourceMap.set(protectedResources.graphContacts.endpoint, protectedResources.graphContacts.scopes);
  protectedResourceMap.set(host() + graphURI, [ {httpMethod: "POST", scopes: ["api://adtakr/Application.Run"]}]);

  return {
      interactionType: InteractionType.Redirect,
      protectedResourceMap,
      authRequest: (msalService, httpReq, originalAuthRequest) => {
          const resource = new URL(httpReq.url).hostname;
          let claim =
              msalService.instance.getActiveAccount()! &&
                  getClaimsFromStorage(
                      `cc.${msalConfig.auth.clientId}.${msalService.instance.getActiveAccount()?.idTokenClaims?.oid
                      }.${resource}`
                  )
                  ? window.atob(
                      getClaimsFromStorage(
                          `cc.${msalConfig.auth.clientId}.${msalService.instance.getActiveAccount()?.idTokenClaims?.oid
                          }.${resource}`
                      )
                  )
                  : undefined; // claims challenge e.g {"access_token":{"xms_cc":{"values":["cp1"]}}}
          return {
              ...originalAuthRequest,
              claims: claim,
          };
      },
  };
}
export function ApolloFactory(httpLink:HttpLink) {
      {
        const basic = setContext((operation, context) => ({
         
        }));
        const auth = setContext((operation, context) => {
          const token = localStorage.getItem('token');
       
          if (token === null) {
            return {};
          } else {
            return {
              headers: {
                Authorization: `Bearer ${token}`,
              },
            };
          }
        });
        
        const link = ApolloLink.from([basic, auth, httpLink.create({ uri: graphURI })]);
        return {
          cache: new InMemoryCache({addTypename: false}),
          
          link: link
          }
        };
      }
...

 providers: [
    {
      provide: APOLLO_FLAGS,
      useValue: {
        useInitialLoading: true, // enable it here
      },
    },{
    provide: APOLLO_OPTIONS,
    useFactory: ApolloFactory ,
    deps: [HttpLink],
    
    },
    {
      provide: MSAL_INSTANCE,
      useFactory: MSALInstanceFactory,
    },
    {
      provide: MSAL_GUARD_CONFIG,
      useFactory: MsalGuardConfigurationFactory,
    },
    {
      provide: MSAL_INTERCEPTOR_CONFIG,
      useFactory: MSALInterceptorConfigFactory,
    },
    MsalService,
    MsalBroadcastService,
    MsalGuard,
    {provide: MAT_DATE_LOCALE, useValue: 'en-GB'}],
  bootstrap: [AppComponent, MsalRedirectComponent]```


export function host() {
    return window.location.origin
}

编辑添加:据我在浏览器调试器中看到的,拦截器配置工厂的代码从未被调用。至少,当我在 Firefox 中向 return 语句添加断点时,断点永远不会触发。

angular apollo msal-angular
1个回答
0
投票

我现在感觉自己像个白痴。

我在提供者中缺少以下内容。

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

这告诉 Angular 使用 msal 拦截器来拦截 http 请求。

© www.soinside.com 2019 - 2024. All rights reserved.