【问题标题】:Bearer Token is not adding to HTTP request - MSAL2 Angular不记名令牌未添加到 HTTP 请求 - MSAL2 Angular
【发布时间】:2022-01-07 10:51:56
【问题描述】:

我将我的项目更新为 MSAL2.0 angular。登录,注销和警卫工作正常。它不会向后端 api 的任何请求添加任何不记名令牌。 MSAL 文档说它会自动添加到请求中。

我正在使用 @azure/msal-angular: "^2.0.5", @azure/msal-browser: "^2.16.1"

以下是我的代码 - app.module.ts

 import { msalConfig } from './Shared/azure-config';
    
    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 MSALGuardConfigFactory(): MsalGuardConfiguration {
      return { 
        interactionType: InteractionType.Redirect,  
      };
    }
    
    export function MSALInterceptorConfigFactory(): MsalInterceptorConfiguration {
  const protectedResourceMap = new Map([ 
    [protectedResources.MainStreetContact.endpoint,protectedResources.MainStreetContact.scopes]
  ])
  return {
    interactionType: InteractionType.Redirect,
    protectedResourceMap
  };
}
    
    @NgModule({
      declarations: [
        AppComponent
      ],
      imports: [
        HttpClientModule,
        BrowserModule,
        UserIdleModule.forRoot({idle: 3600, timeout: 30, ping: 120}),
        AppRoutingModule,
        BrowserAnimationsModule,
        MsalModule
      ],
      providers: [
        {
          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
      ],
      bootstrap: [AppComponent]
    })
    export class AppModule { }

azure-config - 
export const protectedResources = {
    MainStreetContact: {
      endpoint: "https://app.mainstreetcontact.com/",
      scopes: ['access_as_user'],
    },
  }

【问题讨论】:

    标签: angular msal


    【解决方案1】:

    我遇到了同样的问题,经过几个小时的调试,我找到了一个适合我的解决方案。

    1. 将 Web API 的 ClientIdapi://<client_id>/<scope> 添加到受保护的资源映射中。
    2. 如果您从其他模块向 Web API 发送请求,请不要在此处导入 HttpClientModule,因为这样拦截器注册将不起作用(其他模块不会使用拦截器)。李>
    3. 添加日志记录 -> 如果您还有其他问题,那么检测起来会容易得多。 MSAL 提供有关拦截器的日志记录信息,因此您可以判断它是否未被使用。

    【讨论】:

      猜你喜欢
      • 2020-01-24
      • 2020-04-19
      • 1970-01-01
      • 2021-04-13
      • 1970-01-01
      • 2019-10-01
      • 1970-01-01
      • 2021-07-21
      • 2017-03-27
      相关资源
      最近更新 更多