亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

Blazor 添加 HttpClientHandler 以將 Jwt 添加到請求的 HTTP 標頭

Blazor 添加 HttpClientHandler 以將 Jwt 添加到請求的 HTTP 標頭

C#
DIEA 2023-09-16 15:17:09
我將Visual Studio 2019和.Net Core 3.0.0-preview-7與標準 Blazor 客戶端、服務器和共享模板一起使用。在應用程序中,我們的服務器端 WebApi 應用程序將始終要求標頭中存在 JWT 令牌以進行授權。從以下內容來看在 ASP.NET Core 中使用 IHttpClientFactory 發出 HTTP 請求我創建了以下處理程序;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從本地存儲獲取保存的令牌并將其添加到標頭?,F在,此時我不確定該怎么做,就好像我將以下內容添加到Blazor.Client Startup.cs;services.AddTransient<JwtTokenHeaderHandler>();services.AddHttpClient("JwtTokenHandler")    .AddHttpMessageHandler<JwtTokenHeaderHandler>();我收到錯誤消息;“IServiceCollection”不包含“AddHttpClient”的定義,并且找不到接受“IServiceCollection”類型的第一個參數的可訪問擴展方法“AddHttpClient”(您是否缺少 using 指令或程序集引用?)誰能指導我在這里做錯了什么?
查看完整描述

4 回答

?
慕姐8265434

TA貢獻1813條經驗 獲得超2個贊

下面是一個摘錄,在默認 http 客戶端上設置默認請求標頭(通過 DI)。然后,對您的 Web api 的所有調用都將包含不記名令牌:

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")));

? ? }

? ? // ...

}


查看完整回答
反對 回復 2023-09-16
?
心有法竹

TA貢獻1866條經驗 獲得超5個贊

目前您無法在客戶端 Blazor 上使用 IHttpClientFactory。


而且您不必從 HttpMessageHandler (DelegatingHandler) 派生。Blazor 已經做到了。以下是擴展 HttpClient 服務功能的擴展類,以啟用將 Jwt 令牌添加到請求消息標頭的功能...


服務擴展.cs

    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 });

            }

}

下面展示了如何調用 Web Api 上的端點,傳遞從 localStorage 讀取的 Jwt 令牌。(順便說一句,這些版本都沒有數據保護)


索引剃刀

@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));

    }

}

希望這有效...如果沒有,并且您無法解決錯誤,請來這里告訴社區...


查看完整回答
反對 回復 2023-09-16
?
慕容森

TA貢獻1853條經驗 獲得超18個贊

以下將 X-CSRF-TOKEN 標頭添加到 http 請求中:


public class CustomHttpMessageHandler : DelegatingHandler

{

    private readonly IJSRuntime _js;

    public CustomHttpMessageHandler(IJSRuntime js)

    {

        _js = js;

    }


    protected override async Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)

    {

        var afrt = await _js.InvokeAsync<string>("getCookie", ".AFRT");

        request.Headers.Add("X-CSRF-TOKEN", afrt);

        return await base.SendAsync(request, cancellationToken);

    }

}

在 Program.cs 中配置如下:


builder.Services.AddScoped<CustomHttpMessageHandler>();

builder.Services.AddHttpClient("ApiClient", client => client.BaseAddress = new Uri(builder.HostEnvironment.BaseAddress))

    .AddHttpMessageHandler<CustomHttpMessageHandler>();

builder.Services.AddScoped(sp => sp.GetRequiredService<IHttpClientFactory>().CreateClient("ApiClient"));

您需要將 Microsoft.Extensions.Http 包安裝到 Blazor WebAssembly 客戶端。


查看完整回答
反對 回復 2023-09-16
?
蝴蝶不菲

TA貢獻1810條經驗 獲得超4個贊

Microsoft.Extensions.Http您需要包含 AddHttpClient 方法的NuGet 包。使用以下命令安裝它:Install-Package Microsoft.Extensions.Http -Version 3.0.0-preview7.19362.4

看起來,這個 NuGet 包是在服務器端 blazor 中自動提供的,但必須在客戶端 blazor 中單獨安裝。


查看完整回答
反對 回復 2023-09-16
  • 4 回答
  • 0 關注
  • 407 瀏覽

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號