Files
TaskHybrid/Template.Shared/Core/Services/AppAuthenticationStateProvider.cs
2025-05-09 14:43:46 +02:00

56 lines
1.7 KiB
C#

using IntegryApiClient.Core.Domain.Abstraction.Contracts.Account;
using System.Security.Claims;
using Microsoft.AspNetCore.Components.Authorization;
namespace Template.Shared.Core.Services;
public class AppAuthenticationStateProvider : AuthenticationStateProvider
{
private readonly IUserSession _userSession;
private readonly IUserAccountService _userAccountService;
public AppAuthenticationStateProvider(IUserSession userSession, IUserAccountService userAccountService)
{
_userSession = userSession;
_userAccountService = userAccountService;
userAccountService.ExpiredUserSession += (_, _) =>
NotifyAuthenticationStateChanged(LoadAuthenticationState());
}
public override async Task<AuthenticationState> GetAuthenticationStateAsync()
{
return await LoadAuthenticationState();
}
public async void SignOut()
{
await _userAccountService.Logout();
NotifyAuthenticationState();
}
public void NotifyAuthenticationState()
{
NotifyAuthenticationStateChanged(LoadAuthenticationState());
}
private async Task<AuthenticationState> LoadAuthenticationState()
{
if (!await _userSession.IsLoggedIn() || !await _userSession.IsRefreshTokenValid())
{
return new AuthenticationState(
new ClaimsPrincipal(
new ClaimsIdentity()
)
);
}
var claimIdentity = new ClaimsIdentity(_userSession.JwtToken!.Claims, "jwt");
var user = new ClaimsPrincipal(claimIdentity);
var authenticationState = new AuthenticationState(user);
return authenticationState;
}
}