[英]Storing a JWT token in Blazor Client Side
I am trying my first Blazor app, client side, and am battling with authentication.我正在尝试我的第一个 Blazor 应用程序,客户端,并且正在与身份验证作斗争。 I have managed to call my API, get a token, and authenticate in the app.
我已成功拨打我的 API,获取令牌并在应用程序中进行身份验证。 I need to store the JWT token somewhere - and I thought, in the claims, might be OK.
我需要将 JWT 令牌存储在某个地方 - 我认为,在声明中,可能没问题。 (Maybe this is where I go wrong, and it should be somehow, in LocalStorage or something?)
(也许这是我 go 错误的地方,它应该在某种程度上,在 LocalStorage 或其他地方?)
So for my authorisation, I have a AuthenticationStateProvider
, where - things work OK.因此,对于我的授权,我有一个
AuthenticationStateProvider
,其中 - 一切正常。 I get authenticated.我得到认证。 But I am unable to acceess my token.
但是我无法访问我的令牌。
Is this the right place to be adding it?这是添加它的正确位置吗? And if so, why is this code failing me?
如果是这样,为什么这段代码让我失望了?
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??
}
}
My index page is working:我的索引页面正在运行:
<Authorized>
<p>Welcome, @context.User.Identity.Name</p>
</Authorized>
<NotAuthorized>
<p>You're not signed in</p>
</NotAuthorized>
</AuthorizeView>
It shows my name, when logged in, as expected.它按预期显示我的名字,当登录时。
But on a page where I need to send the JWT token to the API, I am trying to find it:但是在我需要将 JWT 令牌发送到 API 的页面上,我试图找到它:
var user = authState.User;
But user
seems to have no 'token' parameter.但
user
似乎没有“令牌”参数。
How should I be storing my JWT, and having access to it when ever I am about to use my http client?我应该如何存储我的 JWT,并在我即将使用我的 http 客户端时访问它?
You save token in local storage of web browser.您将令牌保存在 web 浏览器的本地存储中。 something like this
像这样的
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);
}
}
}
source: https://jasonwatmore.com/post/2020/08/13/blazor-webassembly-jwt-authentication-example-tutorial来源: https://jasonwatmore.com/post/2020/08/13/blazor-webassembly-jwt-authentication-example-tutorial
I suggest you use Blazored library.我建议你使用 Blazored 库。 They provide both local and session storage options.
它们提供本地和 session 存储选项。 I use the latter.
我用后者。 Information on https://github.com/Blazored/SessionStorage
https上的信息://github.com/Blazored/SessionStorage
The following answer is relevant if you are relying on Msal for authentication, such as using it with Azure B2C:如果您依赖 Msal 进行身份验证,例如将其与 Azure B2C 一起使用,则以下答案是相关的:
builder.Services.AddMsalAuthentication(options =>
{
...
options.ProviderOptions.Cache.CacheLocation = "localStorage";
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.