finalizare 1.0
This commit is contained in:
@@ -0,0 +1,47 @@
|
||||
using System.IdentityModel.Tokens.Jwt;
|
||||
using System.Security.Claims;
|
||||
using System.Threading.Tasks;
|
||||
using Blazored.LocalStorage;
|
||||
using Microsoft.AspNetCore.Components.Authorization;
|
||||
|
||||
namespace HealthcareManagerUiWebAssem;
|
||||
|
||||
public class CustomAuthenticationStateProvider(ILocalStorageService localStorageService) : AuthenticationStateProvider
|
||||
{
|
||||
public override async Task<AuthenticationState> GetAuthenticationStateAsync()
|
||||
{
|
||||
var token = await localStorageService.GetItemAsync<string>("authToken");
|
||||
|
||||
if (string.IsNullOrEmpty(token))
|
||||
return new AuthenticationState(new ClaimsPrincipal(new ClaimsIdentity()));
|
||||
|
||||
var claims = ParseClaimsFromJwt(token);
|
||||
var identity = new ClaimsIdentity(claims, "jwt", null, "role");
|
||||
|
||||
var user = new ClaimsPrincipal(identity);
|
||||
|
||||
return new AuthenticationState(user);
|
||||
}
|
||||
|
||||
public void NotifyUserAuthentication(string token)
|
||||
{
|
||||
var claims = ParseClaimsFromJwt(token);
|
||||
var authenticatedUser = new ClaimsPrincipal(new ClaimsIdentity(claims, "jwt", null, "role"));
|
||||
var authState = Task.FromResult(new AuthenticationState(authenticatedUser));
|
||||
|
||||
NotifyAuthenticationStateChanged(authState);
|
||||
}
|
||||
|
||||
public void NotifyUserLogout()
|
||||
{
|
||||
var authState = Task.FromResult(new AuthenticationState(new ClaimsPrincipal(new ClaimsIdentity())));
|
||||
NotifyAuthenticationStateChanged(authState);
|
||||
}
|
||||
|
||||
private IEnumerable<Claim> ParseClaimsFromJwt(string jwt)
|
||||
{
|
||||
var handler = new JwtSecurityTokenHandler();
|
||||
var token = handler.ReadJwtToken(jwt);
|
||||
return token.Claims;
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user