在 Blazor 客户端中存储 JWT 令牌

Cra*_*aig 3 c# asp.net-core blazor

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

因此,对于我的授权,我有一个AuthenticationStateProvider, where - 一切正常。我得到认证。但我无法访问我的令牌。

这是添加它的正确位置吗?如果是这样,为什么这段代码让我失望?

    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??
         
        }
    }
Run Code Online (Sandbox Code Playgroud)

我的索引页正在工作:

    <Authorized>
        <p>Welcome, @context.User.Identity.Name</p>
    </Authorized>
    <NotAuthorized>
        <p>You're not signed in</p>
    </NotAuthorized>
</AuthorizeView>
Run Code Online (Sandbox Code Playgroud)

它在登录时按预期显示我的名字。

但是在我需要将 JWT 令牌发送到 API 的页面上,我试图找到它:


        var user = authState.User;
Run Code Online (Sandbox Code Playgroud)

user似乎没有“令牌”参数。

在此处输入图片说明

我应该如何存储我的 JWT,并在我即将使用我的 http 客户端时访问它?

nhu*_*uvy 5

您将令牌保存在 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);
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

来源:https : //jasonwatmore.com/post/2020/08/13/blazor-webassembly-jwt-authentication-example-tutorial

  • @aguafrommars 每次我们关闭并重新打开浏览器时,会话不会重新初始化吗?每次都必须重新连接似乎会破坏用户体验 (4认同)