Files
FA_WEB/OrdersManagement/CustomAuthenticationStateProvider.cs
2025-02-28 13:33:01 +01:00

52 lines
2.0 KiB
C#

using System.IdentityModel.Tokens.Jwt;
using System.Security.Claims;
using Blazored.LocalStorage;
using Microsoft.AspNetCore.Components.Authorization;
namespace OrdersManagement;
public class CustomAuthenticationStateProvider(ILocalStorageService localStorage) : AuthenticationStateProvider
{
private string? _token;
private ClaimsPrincipal _currentUser = new(new ClaimsIdentity());
public override async Task<AuthenticationState> GetAuthenticationStateAsync()
{
_token = await localStorage.GetItemAsync<string>("authToken");
if (string.IsNullOrEmpty(_token))
{
return await Task.FromResult(new AuthenticationState(new ClaimsPrincipal(new ClaimsIdentity())));
}
var handler = new JwtSecurityTokenHandler();
var jwtToken = handler.ReadJwtToken(_token);
var identity = new ClaimsIdentity(jwtToken.Claims, "jwt", JwtRegisteredClaimNames.Sub, null);
_currentUser = new ClaimsPrincipal(identity);
return await Task.FromResult(new AuthenticationState(_currentUser));
}
public async Task MarkUserAsAuthenticated(string? token)
{
_token = token;
await localStorage.SetItemAsync("authToken", token);
var handler = new JwtSecurityTokenHandler();
var jwtToken = handler.ReadJwtToken(token);
var identity = new ClaimsIdentity(jwtToken.Claims, "jwt", JwtRegisteredClaimNames.Sub, null);
_currentUser = new ClaimsPrincipal(identity);
NotifyAuthenticationStateChanged(Task.FromResult(new AuthenticationState(_currentUser)));
}
public async Task MarkUserAsLoggedOut()
{
_token = null;
await localStorage.RemoveItemAsync("authToken");
_currentUser = new ClaimsPrincipal(new ClaimsIdentity());
NotifyAuthenticationStateChanged(Task.FromResult(new AuthenticationState(_currentUser)));
}
public string? GetToken() => _token;
public ClaimsPrincipal GetCurrentUser() => _currentUser;
}