簡體   English   中英

在 Blazor 客戶端存儲 JWT 令牌

[英]Storing a JWT token in Blazor Client Side

我正在嘗試我的第一個 Blazor 應用程序,客戶端,並且正在與身份驗證作斗爭。 我已成功撥打我的 API,獲取令牌並在應用程序中進行身份驗證。 我需要將 JWT 令牌存儲在某個地方 - 我認為,在聲明中,可能沒問題。 (也許這是我 go 錯誤的地方,它應該在某種程度上,在 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似乎沒有“令牌”參數。

在此處輸入圖像描述

我應該如何存儲我的 JWT,並在我即將使用我的 http 客戶端時訪問它?

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

我建議你使用 Blazored 庫。 它們提供本地和 session 存儲選項。 我用后者。 https上的信息://github.com/Blazored/SessionStorage

如果您依賴 Msal 進行身份驗證,例如將其與 Azure B2C 一起使用,則以下答案是相關的:

builder.Services.AddMsalAuthentication(options =>
{
    ...
    options.ProviderOptions.Cache.CacheLocation = "localStorage";
});

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM