我缺少什么让我的用户通过身份验证?Microsoft.AspNetCore.Authentication.JwtBearer 不处理客户端部分(存储令牌)吗?
在JwtBearer
服务器端运行,它只会验证请求的授权标头,即Authorization: Bearer your_access_token
,而不关心您的 WebAssembly 代码如何运行。因此,您需要使用 jwt accessToken 发送请求。由于教程建议您应该使用localStorage
,让我们存储accessToken
with localStorage
。
因为WebAssembly
还没有访问权限BOM
,所以我们需要一些 javascript 代码作为胶水。为此,请在helper.js
以下添加JwtAuthentication.Client/wwwroot/js/
:
var wasmHelper = {};
wasmHelper.ACCESS_TOKEN_KEY ="__access_token__";
wasmHelper.saveAccessToken = function (tokenStr) {
localStorage.setItem(wasmHelper.ACCESS_TOKEN_KEY,tokenStr);
};
wasmHelper.getAccessToken = function () {
return localStorage.getItem(wasmHelper.ACCESS_TOKEN_KEY);
};
并参考你的脚本JwtAuthentication.Client/wwwroot/index.html
<body>
<app>Loading...</app>
<script src="js/helper.js"></script>
<script src="_framework/blazor.webassembly.js"></script>
</body>
现在,让我们将 javascript 代码包装到 C# 中。创建一个新文件Client/Services/TokenService.cs
:
public class TokenService
{
public Task SaveAccessToken(string accessToken) {
return JSRuntime.Current.InvokeAsync<object>("wasmHelper.saveAccessToken",accessToken);
}
public Task<string> GetAccessToken() {
return JSRuntime.Current.InvokeAsync<string>("wasmHelper.getAccessToken");
}
}
通过以下方式注册此服务:
// file: Startup.cs
services.AddSingleton<TokenService>(myTokenService);
现在我们可以注入TokenService
并Login.cshtml
使用它来保存令牌:
@using JwtAuthentication.Client.Services
// ...
@page "/login"
// ...
@inject TokenService tokenService
// ...
@functions {
public string Email { get; set; } = "";
public string Password { get; set; } = "";
public string Token { get; set; } = "";
/// <summary>
/// response from server
/// </summary>
private class TokenResponse{
public string Token;
}
private async Task SubmitForm()
{
var vm = new TokenViewModel
{
Email = Email,
Password = Password
};
var response = await Http.PostJsonAsync<TokenResponse>("http://localhost:57778/api/Token", vm);
await tokenService.SaveAccessToken(response.Token);
}
}
假设您要在其中发送数据FetchData.cshtml
@functions {
WeatherForecast[] forecasts;
protected override async Task OnInitAsync()
{
var token = await tokenService.GetAccessToken();
Http.DefaultRequestHeaders.Add("Authorization",String.Format("Bearer {0} ",token));
forecasts = await Http.GetJsonAsync<WeatherForecast[]>("api/SampleData/WeatherForecasts");
}
}
结果将是: