Azure AD for Angular + ASP.net web api - Msal Angular HTTP interceptor does not attach token For POST method

Viewed 317

I am using Azure AD for Authentication ( SPA(Angular) and ASP.net core web api ). I have no issues while reading user information or any Get call from Angular. I can see Bearer token gets attached to Request.header by MSAL Interceptor. all working good so far.

When I run Post call to same API, I get unauthorized 401 error for my API.

Can someone tell me what am I missing?

error

app module

1 Answers

I assume you found them, but just in case you can check the relevant examples for angular msal here.

When I went through it my app.module ended up looking, in part, like the following

 providers: [
    AuthService,
    {
      provide: HTTP_INTERCEPTORS,
      useClass: HttpInterceptorService,
      multi: true
    },
    {
      provide: HTTP_INTERCEPTORS,
      useClass: MsalInterceptor,
      multi: true
    },
    PermissionEndpointService,
    {
      provide: MSAL_INSTANCE,
      useFactory: MSALInstanceFactory
    },
    {
      provide: MSAL_GUARD_CONFIG,
      useFactory: MSALGuardConfigFactory
    },
    {
      provide: MSAL_INTERCEPTOR_CONFIG,
      useFactory: MSALInterceptorConfigFactory
    },
    MsalService,
    MsalGuard,
    MsalBroadcastService
  ],
  bootstrap: [AppComponent, MsalRedirectComponent]

Adding the MsalRedirectComponent to the bootstrap wasn't part of the docs but I found it to be helpful to make it start to work. You might try that as well. I'm also not calling forRoot, but instead providing everything that the module's forRoot would provide for you, likely stolen from an earlier example.

Your interceptor config looks like it might also be causing you an issue. The basic idea is that it restricts what destinations you are sending your jwt to. Here is my definition

export function MSALInterceptorConfigFactory(): MsalInterceptorConfiguration {
  const protectedResourceMap = new Map<string, Array<string>>();
  protectedResourceMap.set(`${environment.api_url}/some-anonymous-route/*`, null);
  protectedResourceMap.set(`${environment.api_url}/another-anonymous-route`, null);
  protectedResourceMap.set(environment.api_url, environment.msalConfig.scopes);

  return {
    interactionType: InteractionType.Redirect,
    protectedResourceMap
  };
}

You might try rewriting the way you have it, but maybe I'm reading what you have incorrectly. Something like

{
  const protectedResourceMap = new Map<string, Array<string>>();  
  protectedResourceMap.set(environment.apiBaseUrl, [https://yoursitehere.com/api/user_impersonation]);

  return {
    interactionType: InteractionType.Redirect,
    protectedResourceMap
  };
}

Feel free to comment or add information. I'll see if I can help more.

Related