问题
I have a restful service running on localhost:5002, Identity server on 5000 and Blazor WebAssembly app on localhost:1330. There is probably something going on with they're not all on the same domain.
I can authenticate with my Blazor WebAssembly app (Client not server) Which inturn calls WebApi methods, I get returned, 401 not authorised. I've manually added the bearer token to the requests and it works perfectly returning results etc.
HttpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", "{{BEARER TOKEN VALUE}}");
My main question is. What's the best way to get the Bearer token and pass it on?
回答1:
IMO the best way is to use the IHttpClientFactory
and assign the token by using the built-in BaseAddressAuthorizationMessageHandler
Setup DI
public class Program
{
public static async Task Main(string[] args)
{
var builder = WebAssemblyHostBuilder.CreateDefault(args);
builder.RootComponents.Add<App>("app");
builder.Services.AddOidcAuthentication<RemoteAuthenticationState, RemoteUserAccount>(options =>
{
options.ProviderOptions.Authority = "http://localhost:5000";
options.ProviderOptions.ClientId= "{YOUR CLIENT ID}";
options.ProviderOptions.RedirectUri= "http://localhost:1330/authentication/login-callback";
})
.AddHttpClient("apiClient")
.ConfigureHttpClient(httpClient =>
{
httpClient.BaseAddress = "http://localhost:5002";
})
.AddHttpMessageHandler<BaseAddressAuthorizationMessageHandler>();
await builder.Build().RunAsync();
}
}
Use in Component or Service by injecting an IHttpClientFactory
Component Sample
@inject IHttpClientFactory _factory
@code {
protected override async Task OnInitializedAsync()
{
var client = _factory.CreateClient("apiClient")
var data = await client.GetJsonAsync<Data>("api/data");
}
}
There is multiple way to use IHttpClientFactory
, read Use IHttpClientFactory to implement resilient HTTP requests for more informations.
来源:https://stackoverflow.com/questions/61591696/blazor-webassembly-invoking-protected-webapi-methods-and-relaying-bearer-token