pascx64
pascx64

Reputation: 984

blazor wasm forward authentication to external API

I have a blazor wasm app using AAD authentication, created using : https://learn.microsoft.com/en-us/aspnet/core/blazor/security/webassembly/standalone-with-azure-active-directory?view=aspnetcore-6.0 This part works really well.

I have another asp.net core app (not hosting the wasm app) that I need to forward the authentication to when doing API calls. I want to "know" which user is doing the call (and check that it is true, obviously). I keep getting 401 errors to my API calls. I have added the following code to the client app, hoping this would forward the current user to the http call:

services
   .AddHttpClient("LoginAPI", client => client.BaseAddress = new Uri("https://localhost:7215")) // not the same as the URL hosting the current WASM app
   .AddHttpMessageHandler<BaseAddressAuthorizationMessageHandler>();

services.AddScoped(sp => sp.GetRequiredService<IHttpClientFactory>().CreateClient("LoginAPI"));

In the server app, I added the "UseAuthentication" and "UseAuthorization" as usual, and this:

builder.Services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
    .AddMicrosoftIdentityWebApi(builder.Configuration.GetSection("AzureAd"));

My server appsettings:

"AzureAd": {
  "Instance": "https://login.microsoftonline.com/common",
  "TenantId": "common",
  "ClientId": "***"
}

And my client appsettings:

"AzureAd": {
  "Authority": "https://login.microsoftonline.com/common",
  "ClientId": "***", // same as in the server
  "ValidateAuthority": true
}

Any idea how to make my blazor WASM app authenticate with the other asp.net core API?

Thanks!

Upvotes: 1

Views: 1047

Answers (1)

pascx64
pascx64

Reputation: 984

In case someone else arrives here. I managed to make it work following this : https://stackoverflow.com/a/67147315/1758142.

it led met to another error where the token sent was not valid, I found out that for "https://login.microsoftonline.com/common", I can't use the scope "https://graph.microsoft.com/User.Read". I replace it with both of these: https://graph.microsoft.com/offline_access https://graph.microsoft.com/profile

Upvotes: 1

Related Questions