using System.IdentityModel.Tokens.Jwt; using System.Security.Claims; using Blazored.LocalStorage; using Microsoft.AspNetCore.Components.Authorization; namespace HealthcareManagerUiWebAssem; public class CustomAuthenticationStateProvider(ILocalStorageService localStorageService) : AuthenticationStateProvider { public override async Task GetAuthenticationStateAsync() { var token = await localStorageService.GetItemAsync("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 ParseClaimsFromJwt(string jwt) { var handler = new JwtSecurityTokenHandler(); var token = handler.ReadJwtToken(jwt); return token.Claims; } }