46 lines
1.4 KiB
C#
46 lines
1.4 KiB
C#
using System.Security.Claims;
|
|||
|
|
using Microsoft.AspNetCore.Components.Authorization;
|
||
|
|
|
||
|
|
namespace Heimdall.Web.Services;
|
||
|
|
|
||
|
|
public class HeimdallAuthStateProvider : AuthenticationStateProvider
|
||
|
|
{
|
||
|
|
private readonly AuthState _authState;
|
||
|
|
|
||
|
|
public HeimdallAuthStateProvider(AuthState authState)
|
||
|
|
{
|
||
|
|
_authState = authState;
|
||
|
|
}
|
||
|
|
|
||
|
|
public override Task<AuthenticationState> GetAuthenticationStateAsync()
|
||
|
|
{
|
||
|
|
if (!_authState.IsLoggedIn || _authState.User is null)
|
||
|
|
{
|
||
|
|
return Task.FromResult(new AuthenticationState(new ClaimsPrincipal(new ClaimsIdentity())));
|
||
|
|
}
|
||
|
|
|
||
|
|
var claims = new List<Claim>
|
||
|
|
{
|
||
|
|
new(ClaimTypes.NameIdentifier, _authState.User.Id.ToString()),
|
||
|
|
new(ClaimTypes.Name, _authState.User.DisplayName),
|
||
|
|
new(ClaimTypes.Email, _authState.User.Email),
|
||
|
|
};
|
||
|
|
|
||
|
|
if (_authState.User.Roles is not null)
|
||
|
|
{
|
||
|
|
foreach (var role in _authState.User.Roles)
|
||
|
|
{
|
||
|
|
claims.Add(new Claim(ClaimTypes.Role, role));
|
||
|
|
claims.Add(new Claim("permission", role)); // Map role to permission for policies
|
||
|
|
}
|
||
|
|
}
|
||
|
|
|
||
|
|
var identity = new ClaimsIdentity(claims, "HeimdallAuth");
|
||
|
|
return Task.FromResult(new AuthenticationState(new ClaimsPrincipal(identity)));
|
||
|
|
}
|
||
|
|
|
||
|
|
public void NotifyAuthStateChanged()
|
||
|
|
{
|
||
|
|
NotifyAuthenticationStateChanged(GetAuthenticationStateAsync());
|
||
|
|
}
|
||
|
|
}
|