在Blazor客户端中存储JWT令牌

时间:2020-09-02 03:08:30

标签: c# asp.net-core blazor

我正在尝试我的第一个Blazor应用程序(客户端),并且正在与身份验证进行斗争。我设法调用了我的API,获得了令牌,并在应用程序中进行了身份验证。我需要将JWT令牌存储在某个地方-并且我认为在声明中可能还可以。 (也许这是我出问题的地方,应该以某种方式在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似乎没有'token'参数。

enter image description here

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

2 个答案:

答案 0 :(得分:2)

我建议您使用Blazored库。它们提供本地存储和会话存储选项。我用后者。有关https://github.com/Blazored/SessionStorage

的信息

答案 1 :(得分:1)

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