Files
taxbaik/TaxBaik.Admin/Services/CustomAuthenticationStateProvider.cs
T
kjh2064 164d121992 feat: NavMenu 로그아웃 버튼 + 토큰 갱신 로직
1. NavMenu에 사용자명 표시 및 로그아웃 버튼 추가
2. CustomAuthenticationStateProvider에 토큰 만료 검증 추가
3. Routes.razor 간소화 (AuthorizeRouteView 사용)
4. 미인증 사용자는 _Imports.razor의 [Authorize]로 보호됨

테스트 계정: admin / admin123

Co-Authored-By: Claude Haiku 4.5 <noreply@anthropic.com>
2026-06-26 22:12:04 +09:00

80 lines
2.5 KiB
C#

using System.IdentityModel.Tokens.Jwt;
using System.Security.Claims;
using Microsoft.AspNetCore.Components.Authorization;
namespace TaxBaik.Admin.Services;
public class CustomAuthenticationStateProvider : AuthenticationStateProvider
{
private readonly ILocalStorageService _localStorage;
private readonly AuthService _authService;
private readonly ILogger<CustomAuthenticationStateProvider> _logger;
public CustomAuthenticationStateProvider(ILocalStorageService localStorage, AuthService authService, ILogger<CustomAuthenticationStateProvider> logger)
{
_localStorage = localStorage;
_authService = authService;
_logger = logger;
}
public override async Task<AuthenticationState> GetAuthenticationStateAsync()
{
try
{
var token = await _localStorage.GetItemAsStringAsync("auth_token");
if (string.IsNullOrEmpty(token))
{
return new AuthenticationState(new ClaimsPrincipal(new ClaimsIdentity()));
}
if (IsTokenExpired(token))
{
_logger.LogWarning("토큰 만료됨");
await _localStorage.RemoveItemAsync("auth_token");
return new AuthenticationState(new ClaimsPrincipal(new ClaimsIdentity()));
}
var principal = _authService.ValidateToken(token);
if (principal == null)
{
await _localStorage.RemoveItemAsync("auth_token");
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 token)
{
await _localStorage.SetItemAsStringAsync("auth_token", token);
NotifyAuthenticationStateChanged(GetAuthenticationStateAsync());
}
public async Task LogoutAsync()
{
await _localStorage.RemoveItemAsync("auth_token");
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;
}
}
}