Files
TechHelper/TechHelper.Client/AuthProviders/AuthStateProvider.cs
2025-05-23 19:03:00 +08:00

65 lines
1.8 KiB
C#

using Microsoft.AspNetCore.Components.Authorization;
using System.Security.Claims;
using System.Net.Http.Headers;
using TechHelper.Features;
using Microsoft.JSInterop;
namespace TechHelper.Client.AuthProviders
{
public class AuthStateProvider : AuthenticationStateProvider
{
private readonly HttpClient _httpClient;
private readonly AuthenticationState _anonymous;
private readonly ILocalStorageService _localStorageService;
public AuthStateProvider(ILocalStorageService localStorageService, HttpClient httpClient)
{
_localStorageService = localStorageService;
_httpClient = httpClient;
_anonymous = new AuthenticationState(
new ClaimsPrincipal(new ClaimsIdentity()));
}
public override async Task<AuthenticationState> GetAuthenticationStateAsync()
{
string? token = null;
try
{
token = _localStorageService.GetItem<string>("authToken");
}
catch (Exception ex)
{
Console.WriteLine($"Error accessing LocalStorage or parsing token: {ex.Message}");
return _anonymous;
}
if (string.IsNullOrEmpty(token))
return _anonymous;
_httpClient.DefaultRequestHeaders.Authorization =
new AuthenticationHeaderValue("bearer", token);
return new AuthenticationState(new ClaimsPrincipal(
new ClaimsIdentity(JWTParser.ParseClaimsFromJwt(token), "jwtAuthType")));
}
public void NotifyUserAuthentication(string token)
{
var authenticatedUser = new ClaimsPrincipal(new ClaimsIdentity(
JWTParser.ParseClaimsFromJwt(token), "jwtAuthType"));
var authState = Task.FromResult(new AuthenticationState(authenticatedUser));
NotifyAuthenticationStateChanged(authState);
}
public void NotifyUserLogout()
{
var authState = Task.FromResult(_anonymous);
NotifyAuthenticationStateChanged(authState);
}
}
}