87 lines
2.4 KiB
C#
87 lines
2.4 KiB
C#
using Microsoft.JSInterop;
|
|
using System.IdentityModel.Tokens.Jwt;
|
|
using System.Security.Claims;
|
|
|
|
namespace OnProfNext.Client.Services
|
|
{
|
|
public class AuthService
|
|
{
|
|
private readonly IJSRuntime _js;
|
|
private const string TokenKey = "authToken";
|
|
|
|
public AuthService(IJSRuntime js) => _js = js;
|
|
|
|
public ValueTask SaveTokenAsync(string token) =>
|
|
_js.InvokeVoidAsync("localStorage.setItem", TokenKey, token);
|
|
|
|
public ValueTask<string?> GetTokenAsync() =>
|
|
_js.InvokeAsync<string?>("localStorage.getItem", TokenKey);
|
|
|
|
public async Task LogoutAsync()
|
|
{
|
|
await _js.InvokeVoidAsync("localStorage.removeItem", TokenKey);
|
|
OnAuthStateChanged?.Invoke();
|
|
}
|
|
|
|
public async Task<string?> GetUsernameAsync()
|
|
{
|
|
var token = await GetTokenAsync();
|
|
if (string.IsNullOrWhiteSpace(token))
|
|
{
|
|
return null;
|
|
}
|
|
try
|
|
{
|
|
var handler = new JwtSecurityTokenHandler();
|
|
var jwt = handler.ReadJwtToken(token);
|
|
var usernameClaim = jwt.Claims.FirstOrDefault(c =>
|
|
c.Type == ClaimTypes.Name ||
|
|
c.Type == "unique_name" ||
|
|
c.Type == "name"
|
|
);
|
|
return usernameClaim?.Value;
|
|
}
|
|
catch
|
|
{
|
|
return null;
|
|
}
|
|
}
|
|
|
|
public event Action? OnAuthStateChanged;
|
|
|
|
public async Task NotifyAuthStateChangedAsync()
|
|
{
|
|
OnAuthStateChanged?.Invoke();
|
|
}
|
|
|
|
public async Task LoginAsync(string token)
|
|
{
|
|
await SaveTokenAsync(token);
|
|
OnAuthStateChanged?.Invoke();
|
|
}
|
|
|
|
|
|
|
|
|
|
public async Task<bool> IsLoggedInAsync()
|
|
{
|
|
var token = await GetTokenAsync();
|
|
if (string.IsNullOrWhiteSpace(token))
|
|
{
|
|
return false;
|
|
}
|
|
|
|
try
|
|
{
|
|
var handler = new JwtSecurityTokenHandler();
|
|
var jwt = handler.ReadJwtToken(token);
|
|
var exp = jwt.ValidTo;
|
|
return exp > DateTime.UtcNow;
|
|
}
|
|
catch
|
|
{
|
|
return false;
|
|
}
|
|
}
|
|
}
|
|
} |