c# - Blazor 添加 HttpClientHandler 以将 Jwt 添加到请求的 HTTP header

标签 c# asp.net-core blazor blazor-client-side

我使用的是 Visual Studio 2019.Net Core 3.0.0-preview-7 以及标准 Blazor 客户端、服务器和共享模板。

在应用程序中,我们的服务器端 WebApi 应用程序将始终要求 header 中存在 JWT token 以进行授权。

从查看以下内容

Make HTTP requests using IHttpClientFactory in ASP.NET Core

我创建了以下处理程序;

public class JwtTokenHeaderHandler : DelegatingHandler
{
    private readonly ILocalStorageService _localStorage;

    public JwtTokenHeaderHandler(ILocalStorageService localStorage)
    {
        _localStorage = localStorage;
    }

    protected override async Task<HttpResponseMessage> SendAsync(
        HttpRequestMessage request,
        CancellationToken cancellationToken)
    {
        if (!request.Headers.Contains("bearer"))
        {
            var savedToken = await _localStorage.GetItemAsync<string>("authToken");

            if (!string.IsNullOrWhiteSpace(savedToken))
            {
                request.Headers.Add("bearer", savedToken);
            }
        }

        return await base.SendAsync(request, cancellationToken);
    }
}

我使用 Blazored.LocalStorage 来从 localstorage 获取保存的 token 并将其添加到 header 。

现在,我不确定该怎么做,就好像我将以下内容添加到 Blazor.Client Startup.cs;

services.AddTransient<JwtTokenHeaderHandler>();
services.AddHttpClient("JwtTokenHandler")
    .AddHttpMessageHandler<JwtTokenHeaderHandler>();

我收到错误消息;

'IServiceCollection' does not contain a definition for 'AddHttpClient' and no accessible extension method 'AddHttpClient' accepting a first argument of type 'IServiceCollection' could be found (are you missing a using directive or an assembly reference?)

谁能告诉我我在这里做错了什么?

最佳答案

我找到了一个非常好的教程和示例来演示这一点(包含基于角色/策略的声明): https://chrissainty.com/securing-your-blazor-apps-authentication-with-clientside-blazor-using-webapi-aspnet-core-identity/

下面是一个摘录,在默认 http 客户端上设置默认请求 header (通过 DI)。然后,对您的 Web api 的所有调用都将包含不记名 token :

public class ApiAuthenticationStateProvider : AuthenticationStateProvider
{
    private readonly HttpClient _httpClient;
    private readonly ILocalStorageService _localStorage;

    public ApiAuthenticationStateProvider(HttpClient httpClient, ILocalStorageService localStorage)
    {
        _httpClient = httpClient;
        _localStorage = localStorage;
    }
    public override async Task<AuthenticationState> GetAuthenticationStateAsync()
    {
        var savedToken = await _localStorage.GetItemAsync<string>("authToken");

        if (string.IsNullOrWhiteSpace(savedToken))
        {
            return new AuthenticationState(new ClaimsPrincipal(new ClaimsIdentity()));
        }

        // **************    Set JWT header       ****************
        _httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("bearer", savedToken);
        // *******************************************************

        return new AuthenticationState(new ClaimsPrincipal(new ClaimsIdentity(ParseClaimsFromJwt(savedToken), "jwt")));
    }
    // ...
}

关于c# - Blazor 添加 HttpClientHandler 以将 Jwt 添加到请求的 HTTP header ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57608328/

相关文章:

c# - 多个 ComboBox.DisplayMemberPath 选项?

c# - 在 C# 中调用标量函数

c# - 具有数据库优先方法的 Entity Framework Core 6.0 - 使用 include 时选择中的非必要列

blazor - 服务器端 Blazor 的 WYSIWYG HTML 编辑器

Blazor:如何存储页面状态(所有组件状态)?

c# - 相当于 mono_string_to_utf8() 没有分配和数据复制

c# - 如何在 C# designer.cs 代码中使用常量字符串?

c# - 使用 C# 在 iPhone 上提示 UITextField

forms - 如何实时显示/隐藏元素(Blazor)?

asp.net-core - 使用 ASP.NET Core 2.1 Identity 进行基于权限的授权