简体   繁体   中英

How to add token for Auth0 remote API using IHttpClientFactory Blazor WASM

I have a Blazor WASM application that uses Auth0 Asp.net Hosted authorization model. I can authorize the WASM application properly but I cannot seem to attach the token to my Http requests.

The problematic code is as follows:

Program.cs

builder.Services.AddHttpClient("ServerAPI",
      client => client.BaseAddress = new Uri("https://localhost:7083/"))
    .AddHttpMessageHandler<BaseAddressAuthorizationMessageHandler>();

builder.Services.AddScoped(sp => sp.GetRequiredService<IHttpClientFactory>()
  .CreateClient("ServerAPI"));

client.BaseAddress localhost:7083 is a remote server, so I cannot use BaseAddressAuthorizationMessageHandler to attach the token.

For trouble shootings sake, if I adjust the address as follows:

builder.Services.AddHttpClient("ServerAPI",
      client => client.BaseAddress = new Uri(builder.HostEnvironment.BaseAddress))
    .AddHttpMessageHandler<BaseAddressAuthorizationMessageHandler>();

You can see the token is included in the request包含令牌

When I revert it back to:

builder.Services.AddHttpClient("ServerAPI",
          client => client.BaseAddress = new Uri("https://localhost:7083/"))
        .AddHttpMessageHandler<BaseAddressAuthorizationMessageHandler>();

I don't have the token anymore令牌缺失

My question is how can I configure my IHttpClient to include the token for a remote API? Ideally, I would like to keep this configuration including the token in the middleware Program.cs file. I believe the solution is a custom HttpMessageHandler but I'm not sure how to achieve that.

The solution was to create your own custom AuthorizationMessageHandler class. Here is my implementation incase anyone else has the same issue.

CustomAuthorizationMessageHandler.cs

public class CustomAuthorizationMessageHandler : AuthorizationMessageHandler
    {
        public CustomAuthorizationMessageHandler(IAccessTokenProvider provider,
            NavigationManager navigationManager)
            : base(provider, navigationManager)
        {
            ConfigureHandler(
               authorizedUrls: new[] { "https://localhost:7083" });

        }
    }

Program.cs

builder.Services.AddScoped<CustomAuthorizationMessageHandler>();

builder.Services.AddHttpClient("ServerAPI",
      client => {
          client.BaseAddress = new Uri("https://localhost:7083");
          }
      )
    .AddHttpMessageHandler<CustomAuthorizationMessageHandler>();

builder.Services.AddScoped(sp => sp.GetRequiredService<IHttpClientFactory>()
  .CreateClient("ServerAPI"));

The token is now injected into the Http request在此处输入图像描述

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM