gpt4 book ai didi

c# - 在 Blazor 客户端中存储 JWT token

转载 作者:行者123 更新时间:2023-12-04 00:54:28 24 4
gpt4 key购买 nike

我正在尝试我的第一个 Blazor 应用程序,客户端,并且正在与身份验证作斗争。我已经设法调用我的 API,获取 token 并在应用程序中进行身份验证。我需要将 JWT token 存储在某个地方 - 我认为,在声明中,可能没问题。 (也许这是我出错的地方,应该以某种方式在 LocalStorage 或其他地方?)
因此,对于我的授权,我有一个 AuthenticationStateProvider ,其中 - 一切正常。我得到认证。但我无法访问我的 token 。
这是添加它的正确位置吗?如果是这样,为什么这段代码让我失望?

    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 token 发送到 API 的页面上,我试图找到它:

var user = authState.User;
但是 user 似乎没有 'token' 参数。
enter image description here
我应该如何存储我的 JWT,并在我即将使用我的 http 客户端时访问它?

最佳答案

您将 token 保存在 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

关于c# - 在 Blazor 客户端中存储 JWT token ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63698112/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com