4 回答

TA貢獻(xiàn)1813條經(jīng)驗(yàn) 獲得超2個(gè)贊
下面是一個(gè)摘錄,在默認(rèn) http 客戶端上設(shè)置默認(rèn)請(qǐng)求標(biāo)頭(通過(guò) DI)。然后,對(duì)您的 Web api 的所有調(diào)用都將包含不記名令牌:
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")));
? ? }
? ? // ...
}

TA貢獻(xiàn)1866條經(jīng)驗(yàn) 獲得超5個(gè)贊
目前您無(wú)法在客戶端 Blazor 上使用 IHttpClientFactory。
而且您不必從 HttpMessageHandler (DelegatingHandler) 派生。Blazor 已經(jīng)做到了。以下是擴(kuò)展 HttpClient 服務(wù)功能的擴(kuò)展類(lèi),以啟用將 Jwt 令牌添加到請(qǐng)求消息標(biāo)頭的功能...
服務(wù)擴(kuò)展.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 });
}
}
下面展示了如何調(diào)用 Web Api 上的端點(diǎn),傳遞從 localStorage 讀取的 Jwt 令牌。(順便說(shuō)一句,這些版本都沒(méi)有數(shù)據(jù)保護(hù))
索引剃刀
@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));
}
}
希望這有效...如果沒(méi)有,并且您無(wú)法解決錯(cuò)誤,請(qǐng)來(lái)這里告訴社區(qū)...

TA貢獻(xiàn)1853條經(jīng)驗(yàn) 獲得超18個(gè)贊
以下將 X-CSRF-TOKEN 標(biāo)頭添加到 http 請(qǐng)求中:
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 客戶端。

TA貢獻(xiàn)1810條經(jīng)驗(yàn) 獲得超4個(gè)贊
Microsoft.Extensions.Http
您需要包含 AddHttpClient 方法的NuGet 包。使用以下命令安裝它:Install-Package Microsoft.Extensions.Http -Version 3.0.0-preview7.19362.4
看起來(lái),這個(gè) NuGet 包是在服務(wù)器端 blazor 中自動(dòng)提供的,但必須在客戶端 blazor 中單獨(dú)安裝。
- 4 回答
- 0 關(guān)注
- 440 瀏覽
添加回答
舉報(bào)