AuthorBuddy/Services/CustomAuthStateProvider.cs
2026-06-21 07:52:03 +02:00

40 lines
1.3 KiB
C#

using System.Security.Claims;
using Microsoft.AspNetCore.Components.Authorization;
namespace AuthorBuddy.Web.Services;
public class CustomAuthStateProvider : AuthenticationStateProvider
{
private readonly IAuthService _authService;
private AuthenticationState _anonymous;
public CustomAuthStateProvider(IAuthService authService)
{
_authService = authService;
_anonymous = new AuthenticationState(new ClaimsPrincipal(new ClaimsIdentity()));
}
public override async Task<AuthenticationState> GetAuthenticationStateAsync()
{
var user = await _authService.GetCurrentUserAsync();
if (user != null)
{
var claims = new List<Claim>
{
new Claim(ClaimTypes.Name, user.Name),
new Claim(ClaimTypes.NameIdentifier, user.Id.ToString()),
};
foreach (var role in user.Roles)
claims.Add(new Claim(ClaimTypes.Role, role.ToString()));
var identity = new ClaimsIdentity(claims, "custom");
return new AuthenticationState(new ClaimsPrincipal(identity));
}
return _anonymous;
}
public void NotifyStateChanged()
{
NotifyAuthenticationStateChanged(GetAuthenticationStateAsync());
}
}