Blazor WebAssembly调用受保护的WebAPI方法并中继承载令牌 [英] Blazor WebAssembly invoking protected WebAPI methods and relaying bearer token

查看:266
本文介绍了Blazor WebAssembly调用受保护的WebAPI方法并中继承载令牌的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在localhost:5002上运行了一个宁静的服务,在5000上运行了Identity服务器,在localhost:1330上运行了Blazor WebAssembly应用程序.它们可能不在同一域中,这可能是发生了一些事情.

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.

我可以使用我的Blazor WebAssembly应用程序(客户端而不是服务器)进行身份验证,该应用程序依次调用WebApi方法,我得到了返回,未授权401.我已经将不记名令牌添加到请求中,并且可以完美地返回结果,等等.

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 =新AuthenticationHeaderValue( 承载", {{BEARER令牌值}}");

我的主要问题是.获取Bearer令牌并将其传递的最佳方法是什么?

My main question is. What's the best way to get the Bearer token and pass it on?

推荐答案

IMO最好的方法是使用 IHttpClientFactory 并使用内置的 BaseAddressAuthorizationMessageHandler

IMO the best way is to use the IHttpClientFactory and assign the token by using the built-in BaseAddressAuthorizationMessageHandler

设置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();
    }
}

使用在组件或服务通过注入<代码> IHttpClientFactory

Use in Component or Service by injecting an IHttpClientFactory

组件样本

@inject IHttpClientFactory _factory
@code {
    protected override async Task OnInitializedAsync()
    {
        var client = _factory.CreateClient("apiClient")
        var data = await client.GetJsonAsync<Data>("api/data");
    }
}

有多种使用 IHttpClientFactory 的方法,请阅读

There is multiple way to use IHttpClientFactory, read Use IHttpClientFactory to implement resilient HTTP requests for more informations.

这篇关于Blazor WebAssembly调用受保护的WebAPI方法并中继承载令牌的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆