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>();
}
這只是一個想法,您應該考慮它并使其適應您自己的解決方案。
- 1 回答
- 0 關注
- 120 瀏覽
添加回答
舉報