我使用的是 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/