C# 在Blazor客户端存储JWT令牌

C# 在Blazor客户端存储JWT令牌,c#,asp.net-core,blazor,C#,Asp.net Core,Blazor,我正在尝试我的第一个Blazor应用程序,客户端,正在与身份验证进行斗争。我已经设法调用我的API,获取令牌,并在应用程序中进行身份验证。我需要将JWT令牌存储在某个地方——我认为,在声明中,可能还可以。(也许这就是我出错的地方,而且应该是在本地存储或其他地方。) 因此,对于我的授权,我有一个AuthenticationStateProvider,其中-一切正常。我得到认证。但我无法使用我的代币 这是添加它的正确位置吗?如果是这样,为什么这个代码让我失望 public class Cus

我正在尝试我的第一个Blazor应用程序,客户端,正在与身份验证进行斗争。我已经设法调用我的API,获取令牌,并在应用程序中进行身份验证。我需要将JWT令牌存储在某个地方——我认为,在声明中,可能还可以。(也许这就是我出错的地方,而且应该是在本地存储或其他地方。)

因此,对于我的授权,我有一个
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??
         
        }
    }
但是
user
似乎没有“token”参数


当我要使用http客户端时,我应该如何存储JWT并访问它?

您可以将令牌保存在web浏览器的本地存储中。像这样的

使用Microsoft.JSInterop;
使用System.Text.Json;
使用System.Threading.Tasks;
命名空间BlazorApp.Services
{
公共接口ILocalStorageService
{
任务GetItem(字符串键);
任务集合项(字符串键,T值);
任务移除项(字符串键);
}
公共类LocalStorageService:ILocalStorageService
{
私有ijsruntimejsu运行时;
公共LocalStorageService(IJSRuntime jsRuntime)
{
_jsRuntime=jsRuntime;
}
公共异步任务GetItem(字符串键)
{
var json=awaitu jsRuntime.InvokeAsync(“localStorage.getItem”,key);
if(json==null)
返回默认值;
返回JsonSerializer.Deserialize(json);
}
公共异步任务SetItem(字符串键,T值)
{
wait_jsRuntime.InvokeVoidAsync(“localStorage.setItem”,key,JsonSerializer.Serialize(value));
}
公共异步任务RemoveItem(字符串键)
{
wait_jsRuntime.InvokeVoidAsync(“localStorage.removietem”,key);
}
}
}

来源:

我建议您使用Blazored库。它们提供本地和会话存储选项。我使用后者。有关令牌的信息应存储在会话中IMO@aguafrommars不是每次我们关闭并重新打开浏览器时都会重新初始化会话吗?似乎必须重新连接每一个服务器会破坏用户体验time@pascx64如果会话cookie仍然有效,则用户在关闭浏览器后不必重新连接,SSO仍应工作。OAuth令牌由默认Blazor OAuth handler存储在会话存储中。为什么不使用标识Cookie身份验证?将访问令牌存储在localStorage或sessionStorage(js)中,可以使您网页上包含的每个javascript文件都可以访问该令牌
    <Authorized>
        <p>Welcome, @context.User.Identity.Name</p>
    </Authorized>
    <NotAuthorized>
        <p>You're not signed in</p>
    </NotAuthorized>
</AuthorizeView>

        var user = authState.User;