36 lines
1.1 KiB
C#
36 lines
1.1 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 identity = new ClaimsIdentity(new[]
|
|
{
|
|
new Claim(ClaimTypes.Name, user.Name),
|
|
new Claim(ClaimTypes.NameIdentifier, user.Id.ToString()),
|
|
}, "custom");
|
|
return new AuthenticationState(new ClaimsPrincipal(identity));
|
|
}
|
|
return _anonymous;
|
|
}
|
|
|
|
public void NotifyStateChanged()
|
|
{
|
|
NotifyAuthenticationStateChanged(GetAuthenticationStateAsync());
|
|
}
|
|
}
|