using System.IdentityModel.Tokens.Jwt; using System.Security.Claims; using Microsoft.AspNetCore.Components.Authorization; namespace TaxBaik.Web.Services; public class CustomAuthenticationStateProvider : AuthenticationStateProvider { private readonly ILocalStorageService _localStorage; private readonly AuthService _authService; private readonly ILogger _logger; public CustomAuthenticationStateProvider(ILocalStorageService localStorage, AuthService authService, ILogger logger) { _localStorage = localStorage; _authService = authService; _logger = logger; } public override async Task GetAuthenticationStateAsync() { try { var accessToken = await _localStorage.GetItemAsStringAsync("accessToken"); if (string.IsNullOrEmpty(accessToken)) { return new AuthenticationState(new ClaimsPrincipal(new ClaimsIdentity())); } if (IsTokenExpired(accessToken)) { _logger.LogWarning("Access token 만료됨"); await LogoutAsync(); return new AuthenticationState(new ClaimsPrincipal(new ClaimsIdentity())); } var principal = _authService.ValidateToken(accessToken); if (principal == null) { await LogoutAsync(); return new AuthenticationState(new ClaimsPrincipal(new ClaimsIdentity())); } return new AuthenticationState(principal); } catch (Exception ex) { _logger.LogError(ex, "인증 상태 조회 중 오류 발생"); return new AuthenticationState(new ClaimsPrincipal(new ClaimsIdentity())); } } public async Task LoginAsync(string accessToken, string refreshToken, int expiresIn) { await _localStorage.SetItemAsStringAsync("accessToken", accessToken); await _localStorage.SetItemAsStringAsync("refreshToken", refreshToken); await _localStorage.SetItemAsStringAsync("tokenExpiry", DateTime.UtcNow.AddSeconds(expiresIn).Ticks.ToString()); NotifyAuthenticationStateChanged(GetAuthenticationStateAsync()); } public async Task LogoutAsync() { await _localStorage.RemoveItemAsync("accessToken"); await _localStorage.RemoveItemAsync("refreshToken"); await _localStorage.RemoveItemAsync("tokenExpiry"); NotifyAuthenticationStateChanged(GetAuthenticationStateAsync()); } private bool IsTokenExpired(string token) { try { var handler = new JwtSecurityTokenHandler(); var jwtToken = handler.ReadJwtToken(token); return jwtToken.ValidTo < DateTime.UtcNow; } catch { return true; } } }