Blazor WebAssembly invoking protected WebAPI methods and relaying bearer token

青春壹個敷衍的年華 提交于 2021-01-28 20:30:54

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!