亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

使用 Blazor 和 Refresh Token 實現短暫的 Jwt

使用 Blazor 和 Refresh Token 實現短暫的 Jwt

C#
楊魅力 2023-09-16 17:23:35
我們目前正在開發一個Blazor應用程序,該應用程序使用帶有刷新令牌的短期(10 分鐘)Jwt 進行保護。目前我們已經實現了 Jwt,通過 Blazor 服務器端 Web api 可以登錄、生成 Jwt 并生成刷新令牌。從客戶端我使用了以下鏈接;使用客戶端 Blazor 進行身份驗證并擴展ApiAuthenticationStateProvider.cs如下;public class ApiAuthenticationStateProvider : AuthenticationStateProvider{    private readonly HttpClient _httpClient;    private readonly ILocalStorageService _localStorage;    public ApiAuthenticationStateProvider(HttpClient httpClient, ILocalStorageService localStorage)    {        _httpClient = httpClient;        _localStorage = localStorage;    }    public override async Task<AuthenticationState> GetAuthenticationStateAsync()    {        var savedToken = await _localStorage.GetItemAsync<string>("authToken");        var refreshToken = await _localStorage.GetItemAsync<string>("refreshToken");        if (string.IsNullOrWhiteSpace(savedToken) || string.IsNullOrWhiteSpace(refreshToken))        {            return new AuthenticationState(new ClaimsPrincipal(new ClaimsIdentity()));        }        var userResponse = await _httpClient.GetAsync<UserModel>("api/accounts/user", savedToken);        if(userResponse.HasError)        {            var response = await _httpClient.PostAsync<LoginResponse>("api/login/refreshToken", new RefreshTokenModel { RefreshToken = refreshToken });            //check result now            if (!response.HasError)            {                await _localStorage.SetItemAsync("authToken", response.Result.AccessToken);                await _localStorage.SetItemAsync("refreshToken", response.Result.RefreshToken);                userResponse = await _httpClient.GetAsync<UserModel>("api/accounts/user", response.Result.AccessToken);            }但是,我遇到的第二個問題是,如果 Jwt 在此調用期間過期,我將需要調用以使用刷新令牌來獲取新的 Jwt。有沒有辦法可以使用中間件來執行此操作,以避免每次調用時都檢查 401,然后以這種方式更新令牌?
查看完整描述

1 回答

?
慕后森

TA貢獻1802條經驗 獲得超5個贊

我們經常將 Blazor 視為 MVC,但事實并非如此。它更像是在瀏覽器內運行的桌面應用程序。我以這種方式使用 JWT 和更新令牌:登錄后,我有一個無限循環,正在 ping 后端并保持會話并更新令牌。簡化:


class JWTAuthenticationStateProvider : AuthenticationStateProvider

{

? ? private bool IsLogedIn = false;

? ? private CustomCredentials credentials = null;

? ? // private ClaimsPrincipal currentClaimsPrincipal = null; (optinally)

? ? public Task Login( string user, string password )

? ? {

? ? ? ? ?credentials = go_backend_login_service( user, password );

? ? ? ? ?// do stuff with credentials and claims

? ? ? ? ?// I raise event here to notify login

? ? ? ? ?keepSession( );

? ? }

? ? public Task Logout(? )

? ? {

? ? ? ? ?go_bakcend_logout_service( credentials );

? ? ? ? ?// do stuff with claims

? ? ? ? ?IsLogedIn = false;

? ? ? ? ?// I raise event here to notify logout

? ? }

? ? public override Task<AuthenticationState> GetAuthenticationStateAsync()

? ? {

? ? ? ? // make a response from credentials or currentClaimsPrincipal

? ? }

? ? private async void KeepSession()

? ? {

? ? ? ? while(IsLogedIn)

? ? ? ? {

? ? ? ? ? ? credentials = go_backend_renewingJWT_service( credentials );

? ? ? ? ? ? // do stuff with new credentials: check are ok, update IsLogedIn, ...

? ? ? ? ? ? // I raise event here if server says logout

? ? ? ? ? ? await Task.Delay(1000);? // sleep for a while.

? ? ? ? }

? ? }

}

記得通過DI注冊組件:


public void ConfigureServices(IServiceCollection services)

{

? ? // ... other services added here ...


? ? // One JWTAuthenticationStateProvider for each connection on server side.

? ? // A singleton for clientside.

? ? services.AddScoped<AuthenticationStateProvider,?

? ? ? ? ? ? ? ? ? ? ? ?JWTAuthenticationStateProvider>();

}

這只是一個想法,您應該考慮它并使其適應您自己的解決方案。

查看完整回答
反對 回復 2023-09-16
  • 1 回答
  • 0 關注
  • 120 瀏覽

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號