1 回答

TA貢獻(xiàn)1802條經(jīng)驗(yàn) 獲得超5個(gè)贊
我們經(jīng)常將 Blazor 視為 MVC,但事實(shí)并非如此。它更像是在瀏覽器內(nèi)運(yùn)行的桌面應(yīng)用程序。我以這種方式使用 JWT 和更新令牌:登錄后,我有一個(gè)無限循環(huán),正在 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>();
}
這只是一個(gè)想法,您應(yīng)該考慮它并使其適應(yīng)您自己的解決方案。
- 1 回答
- 0 關(guān)注
- 118 瀏覽
添加回答
舉報(bào)