47 lines
1.6 KiB
C#
47 lines
1.6 KiB
C#
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;
|
|
}
|
|
} |