63 lines
2.3 KiB
C#
63 lines
2.3 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 Task<AuthenticationState> GetAuthenticationStateAsync()
|
|
{
|
|
if (string.IsNullOrEmpty(_token))
|
|
{
|
|
return Task.FromResult(new AuthenticationState(new ClaimsPrincipal(new ClaimsIdentity())));
|
|
}
|
|
|
|
var handler = new JwtSecurityTokenHandler();
|
|
var jwtToken = handler.ReadJwtToken(_token);
|
|
var identity = new ClaimsIdentity(jwtToken.Claims, "jwt");
|
|
_currentUser = new ClaimsPrincipal(identity);
|
|
return 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");
|
|
_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 async Task InitializeAsync()
|
|
{
|
|
_token = await localStorage.GetItemAsync<string>("authToken");
|
|
|
|
if (!string.IsNullOrEmpty(_token))
|
|
{
|
|
var handler = new JwtSecurityTokenHandler();
|
|
var jwtToken = handler.ReadJwtToken(_token);
|
|
var identity = new ClaimsIdentity(jwtToken.Claims, "jwt");
|
|
_currentUser = new ClaimsPrincipal(identity);
|
|
NotifyAuthenticationStateChanged(Task.FromResult(new AuthenticationState(_currentUser)));
|
|
}
|
|
}
|
|
|
|
public string? GetToken() => _token;
|
|
}
|
|
|