using Microsoft.AspNetCore.Components.Authorization; using Microsoft.AspNetCore.Components.Server.ProtectedBrowserStorage; using System.Security.Claims; namespace Tagger.Service; public class CustomAuthStateProvider : AuthenticationStateProvider { private readonly ProtectedSessionStorage SessionStorage; private ClaimsPrincipal Anonymous = new(new ClaimsIdentity()); public CustomAuthStateProvider(ProtectedSessionStorage sessionStorage) { SessionStorage = sessionStorage; } public override async Task GetAuthenticationStateAsync() { var userSessionStorageResult = await SessionStorage.GetAsync(nameof(User)); if(!userSessionStorageResult.Success || userSessionStorageResult.Value is null) return new AuthenticationState(Anonymous); var claimPrincipal = new ClaimsPrincipal(new ClaimsIdentity(new List { new Claim(ClaimTypes.Name, userSessionStorageResult.Value.Name) })); return new(claimPrincipal); } public async Task SetSession(User? user) { if(user is null) await SessionStorage.DeleteAsync(nameof(User)); else await SessionStorage.SetAsync(nameof(User), user); } }