using Blazored.LocalStorage; using Microsoft.AspNetCore.Components.Authorization; using System.IdentityModel.Tokens.Jwt; using System.Security.Claims; namespace Customer.Blazor.Providers { public class APIAuthenticationStateProvider : AuthenticationStateProvider { private readonly ILocalStorageService _localStorageService; private ClaimsPrincipal _anonymous = new ClaimsPrincipal(new ClaimsIdentity()); private readonly JwtSecurityTokenHandler _jwtSecurityTokenHandler; public APIAuthenticationStateProvider(ILocalStorageService localStorageService) { // LOCAL WEB STORAGE _localStorageService = localStorageService; _jwtSecurityTokenHandler = new JwtSecurityTokenHandler(); } public override async Task GetAuthenticationStateAsync() { try { // ARE WE LOGGED IN - HAVE WE GOT A TOKEN? var savedToken = await _localStorageService.GetItemAsync("authToken"); if (string.IsNullOrWhiteSpace(savedToken)) { // NO return new AuthenticationState(_anonymous); } // YES var tokenContent = _jwtSecurityTokenHandler.ReadJwtToken(savedToken); var claims = tokenContent.Claims; var user = new ClaimsPrincipal(new ClaimsIdentity(claims, "jwt")); return await Task.FromResult(new AuthenticationState(user)); } catch { // ERROR - NO return new AuthenticationState(_anonymous); } } public async Task MarkUserAsAuthenticated(string token) { // SUCCESS - SAVE THE JWT TOKEN INTO THE LOCAL WEB STORAGE await _localStorageService.SetItemAsync("authToken", token); // GET ALL USER CLAIMS var tokenContent = _jwtSecurityTokenHandler.ReadJwtToken(token); var claims = tokenContent.Claims; var user = new ClaimsPrincipal(new ClaimsIdentity(claims, "jwt")); // UPDATE STATE var state = new AuthenticationState(user); NotifyAuthenticationStateChanged(Task.FromResult(state)); } public async Task MarkUserAsLoggedOut() { // REMOVE JWT TOKEN FROM LOCAL WEB STORAGE try { await _localStorageService.RemoveItemAsync("authToken"); } catch { } // UPDATE STATE var authState = Task.FromResult(new AuthenticationState(_anonymous)); NotifyAuthenticationStateChanged(authState); } } }