[英]Storing a JWT token in Blazor Client Side
我正在尝试我的第一个 Blazor 应用程序,客户端,并且正在与身份验证作斗争。 我已成功拨打我的 API,获取令牌并在应用程序中进行身份验证。 我需要将 JWT 令牌存储在某个地方 - 我认为,在声明中,可能没问题。 (也许这是我 go 错误的地方,它应该在某种程度上,在 LocalStorage 或其他地方?)
因此,对于我的授权,我有一个AuthenticationStateProvider
,其中 - 一切正常。 我得到认证。 但是我无法访问我的令牌。
这是添加它的正确位置吗? 如果是这样,为什么这段代码让我失望了?
public class CustomAuthenticationStaterProvider : AuthenticationStateProvider
{
public override Task<AuthenticationState> GetAuthenticationStateAsync()
{
var identity = new ClaimsIdentity();
var user = new ClaimsPrincipal(identity);
return Task.FromResult(new AuthenticationState(user));
}
public void AuthenticateUser(AuthenticationResponse request)
{
if (request.ResponseDetails.IsSuccess == false)
return;
var identity = new ClaimsIdentity(new[]
{
new Claim("token", request.Token),
new Claim(ClaimTypes.Email, request.Email),
new Claim(ClaimTypes.Name, $"{request.Firstname} {request.Surname}"),
}, "apiauth_type");
var user = new ClaimsPrincipal(identity);
NotifyAuthenticationStateChanged(Task.FromResult(new AuthenticationState(user)));
}
public void LogoutUser()
{
// Hwo??
}
}
我的索引页面正在运行:
<Authorized>
<p>Welcome, @context.User.Identity.Name</p>
</Authorized>
<NotAuthorized>
<p>You're not signed in</p>
</NotAuthorized>
</AuthorizeView>
它按预期显示我的名字,当登录时。
但是在我需要将 JWT 令牌发送到 API 的页面上,我试图找到它:
var user = authState.User;
但user
似乎没有“令牌”参数。
我应该如何存储我的 JWT,并在我即将使用我的 http 客户端时访问它?
您将令牌保存在 web 浏览器的本地存储中。 像这样的
using Microsoft.JSInterop;
using System.Text.Json;
using System.Threading.Tasks;
namespace BlazorApp.Services
{
public interface ILocalStorageService
{
Task<T> GetItem<T>(string key);
Task SetItem<T>(string key, T value);
Task RemoveItem(string key);
}
public class LocalStorageService : ILocalStorageService
{
private IJSRuntime _jsRuntime;
public LocalStorageService(IJSRuntime jsRuntime)
{
_jsRuntime = jsRuntime;
}
public async Task<T> GetItem<T>(string key)
{
var json = await _jsRuntime.InvokeAsync<string>("localStorage.getItem", key);
if (json == null)
return default;
return JsonSerializer.Deserialize<T>(json);
}
public async Task SetItem<T>(string key, T value)
{
await _jsRuntime.InvokeVoidAsync("localStorage.setItem", key, JsonSerializer.Serialize(value));
}
public async Task RemoveItem(string key)
{
await _jsRuntime.InvokeVoidAsync("localStorage.removeItem", key);
}
}
}
来源: https://jasonwatmore.com/post/2020/08/13/blazor-webassembly-jwt-authentication-example-tutorial
我建议你使用 Blazored 库。 它们提供本地和 session 存储选项。 我用后者。 https上的信息://github.com/Blazored/SessionStorage
如果您依赖 Msal 进行身份验证,例如将其与 Azure B2C 一起使用,则以下答案是相关的:
builder.Services.AddMsalAuthentication(options =>
{
...
options.ProviderOptions.Cache.CacheLocation = "localStorage";
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.