Blazor添加HttpClientHandler以根据请求将Jwt添加到HTTP标头 [英] Blazor Adding HttpClientHandler to add Jwt to HTTP Header on requests

查看:842
本文介绍了Blazor添加HttpClientHandler以根据请求将Jwt添加到HTTP标头的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我将Visual Studio 2019.Net Core 3.0.0-preview-7与标准Blazor客户端,服务器和共享模板一起使用.

I am using the Visual Studio 2019 and .Net Core 3.0.0-preview-7 with the standard Blazor Client, Server and Shared templates.

在该应用程序中,我们的服务器端WebApi应用程序将始终要求在标题中存在JWT令牌以进行授权.

In the application our server side WebApi application will always require a JWT token to be present in the header for authorization.

通过查看以下内容

使用IHttpClientFactory进行HTTP请求ASP.NET Core

我创建了以下处理程序;

I created the following handler;

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从本地存储中获取保存的令牌并将其添加到标头中.

Where I use Blazored.LocalStorage to get the saved token from localstorage and add it to the header.

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

Now, at this point I am not sure what to do as if I add the following to the Blazor.Client Startup.cs;

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

我收到错误消息;

"IServiceCollection"不包含"AddHttpClient"的定义 并且没有可访问的扩展方法'AddHttpClient'接受第一个 可以找到类型为"IServiceCollection"的参数(您是否丢失了 using指令还是程序集引用?)

'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?)

任何人都可以将我引到我在这里做错了什么吗?

Can anyone direct me to what I am doing wrong here?

推荐答案

@p> Matthew Flynn,目前您不能在客户端Blazor上使用IHttpClientFactory.

@Matthew Flynn, currently you can't use IHttpClientFactory on client-side Blazor.

您不必从HttpMessageHandler(DelegatingHandler)派生. Blazor已经做到了.以下是n扩展类,用于扩展HttpClient服务的功能,以便能够将Jwt令牌添加到请求消息的标头...

And you don't have to derive from HttpMessageHandler (DelegatingHandler). It has already been done by Blazor. The following is n extension class to extend the functionality of the HttpClient service to enable the ability to add the Jwt token to the header of the request message...

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Net.Http;
    using System.Net.Http.Headers;
    using System.Security.Claims;
    using System.Text;
    using System.Text.Json.Serialization;
    using System.Threading.Tasks;
    using Microsoft.AspNetCore.Components;
    using Microsoft.Extensions.DependencyInjection;

 public static class ServiceExtensions
    {    
     public static async Task<T> GetJsonAsync<T>(this HttpClient httpClient, string url, AuthenticationHeaderValue authorization)
            {
                var request = new HttpRequestMessage(HttpMethod.Get, url);
                request.Headers.Authorization = authorization;

                var response = await httpClient.SendAsync(request);
                var responseBytes = await response.Content.ReadAsByteArrayAsync();
                return JsonSerializer.Parse<T>(responseBytes, new JsonSerializerOptions { PropertyNamingPolicy = JsonNamingPolicy.CamelCase });
            }
}

以下显示了如何通过从本地存储读取的Jwt令牌来调用Web Api上的终结点. (顺便说一下,这些版本均未获得数据保护)

The following show how to call an endpoint on your Web Api, passing the Jwt token which is read from the localStorage. (incidentally, none of these versions is secured with data protection)

@page "/"

@inject ILocalStorageService localStorage
@inject HttpClient Http

<div class="mdc-card main-content-card">
    <h1 class="@MdcTypography.H4">Hello, world!</h1>

    Welcome to your new app.
</div>

// Razor content to display emloyees come here.....

@code {
Employee[] employees;

    protected override async Task OnInitAsync()
    {
        var token = await localStorage.GetTokenAsync();
        employees = await Http.GetJsonAsync<Employee[]>(
            "api/employees",
            new AuthenticationHeaderValue("Bearer", token));
    }
}

希望这行得通...如果没有,您将无法解决thr错误,请到这里告诉社区有关此事...

Hope this works... If not, and you can't solve thr errors, come here and tell the community about it...

这篇关于Blazor添加HttpClientHandler以根据请求将Jwt添加到HTTP标头的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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