39 lines
1.3 KiB
C#
39 lines
1.3 KiB
C#
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<AuthenticationState> GetAuthenticationStateAsync()
|
|
{
|
|
var userSessionStorageResult = await SessionStorage.GetAsync<User>(nameof(User));
|
|
|
|
if(!userSessionStorageResult.Success || userSessionStorageResult.Value is null)
|
|
return new AuthenticationState(Anonymous);
|
|
|
|
var claimPrincipal = new ClaimsPrincipal(new ClaimsIdentity(new List<Claim>
|
|
{
|
|
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);
|
|
}
|
|
}
|