fix: Critical runtime bug - TokenRefreshHandler JS interop in Blazor Server
TaxBaik CI/CD / build-and-deploy (push) Successful in 47s
TaxBaik CI/CD / build-and-deploy (push) Successful in 47s
**Problem:**
TokenRefreshHandler (DelegatingHandler) runs on a non-circuit thread.
ILocalStorageService (JS interop) only works during component render.
Production: 401 response → token refresh → JS interop fails silently.
**Solution:**
1. ITokenStore - Scoped in-memory token store (no JS interop)
- Properties: AccessToken, RefreshToken, TokenExpiryTicks
- Method: IsAccessTokenExpired()
2. TokenStore implementation
- Replaces localStorage as primary token source
- DelegatingHandler reads/writes only to TokenStore
- Pages reload → GetAuthenticationStateAsync restores from localStorage
3. CustomAuthenticationStateProvider
- Accepts ITokenStore injection
- LoginAsync: Write to both TokenStore + localStorage
- LogoutAsync: Clear both
- GetAuthenticationStateAsync: Read from TokenStore first, fallback to localStorage
4. AdminDashboardClient BaseAddress fix
- Was: new Uri("/taxbaik/api/") - relative URI (runtime error)
- Now: Configured in Program.cs as absolute URI
- Program.cs: AddHttpClient(..., client => client.BaseAddress = new Uri("http://localhost:5001/taxbaik/api/"))
**Architecture:**
- TokenStore: Scoped in-memory (DelegatingHandler use)
- localStorage: Persistent (page reload recovery)
- Pattern: Server-side token management without JS interop
This fixes the cascading failure that would occur on any 401 in production.
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
This commit is contained in:
@@ -67,9 +67,13 @@ builder.Services.AddAuthorization();
|
|||||||
builder.Services.AddAuthorizationCore();
|
builder.Services.AddAuthorizationCore();
|
||||||
|
|
||||||
// HTTP Client for API (with automatic token refresh)
|
// HTTP Client for API (with automatic token refresh)
|
||||||
|
builder.Services.AddScoped<ITokenStore, TokenStore>();
|
||||||
builder.Services.AddScoped<TokenRefreshHandler>();
|
builder.Services.AddScoped<TokenRefreshHandler>();
|
||||||
builder.Services.AddHttpClient<IApiClient, ApiClient>();
|
builder.Services.AddHttpClient<IApiClient, ApiClient>();
|
||||||
builder.Services.AddHttpClient<IAdminDashboardClient, AdminDashboardClient>()
|
builder.Services.AddHttpClient<IAdminDashboardClient, AdminDashboardClient>(client =>
|
||||||
|
{
|
||||||
|
client.BaseAddress = new Uri("http://localhost:5001/taxbaik/api/");
|
||||||
|
})
|
||||||
.AddHttpMessageHandler<TokenRefreshHandler>();
|
.AddHttpMessageHandler<TokenRefreshHandler>();
|
||||||
|
|
||||||
// UI & 캐시
|
// UI & 캐시
|
||||||
|
|||||||
@@ -26,7 +26,6 @@ public class AdminDashboardClient : IAdminDashboardClient
|
|||||||
{
|
{
|
||||||
_http = http;
|
_http = http;
|
||||||
_logger = logger;
|
_logger = logger;
|
||||||
_http.BaseAddress = new Uri("/taxbaik/api/");
|
|
||||||
}
|
}
|
||||||
|
|
||||||
public async Task<AdminDashboardSummary> GetSummaryAsync(CancellationToken ct = default)
|
public async Task<AdminDashboardSummary> GetSummaryAsync(CancellationToken ct = default)
|
||||||
|
|||||||
@@ -7,12 +7,18 @@ namespace TaxBaik.Web.Services;
|
|||||||
public class CustomAuthenticationStateProvider : AuthenticationStateProvider
|
public class CustomAuthenticationStateProvider : AuthenticationStateProvider
|
||||||
{
|
{
|
||||||
private readonly ILocalStorageService _localStorage;
|
private readonly ILocalStorageService _localStorage;
|
||||||
|
private readonly ITokenStore _tokenStore;
|
||||||
private readonly AuthService _authService;
|
private readonly AuthService _authService;
|
||||||
private readonly ILogger<CustomAuthenticationStateProvider> _logger;
|
private readonly ILogger<CustomAuthenticationStateProvider> _logger;
|
||||||
|
|
||||||
public CustomAuthenticationStateProvider(ILocalStorageService localStorage, AuthService authService, ILogger<CustomAuthenticationStateProvider> logger)
|
public CustomAuthenticationStateProvider(
|
||||||
|
ILocalStorageService localStorage,
|
||||||
|
ITokenStore tokenStore,
|
||||||
|
AuthService authService,
|
||||||
|
ILogger<CustomAuthenticationStateProvider> logger)
|
||||||
{
|
{
|
||||||
_localStorage = localStorage;
|
_localStorage = localStorage;
|
||||||
|
_tokenStore = tokenStore;
|
||||||
_authService = authService;
|
_authService = authService;
|
||||||
_logger = logger;
|
_logger = logger;
|
||||||
}
|
}
|
||||||
@@ -21,14 +27,31 @@ public class CustomAuthenticationStateProvider : AuthenticationStateProvider
|
|||||||
{
|
{
|
||||||
try
|
try
|
||||||
{
|
{
|
||||||
var accessToken = await _localStorage.GetItemAsStringAsync("accessToken");
|
var accessToken = _tokenStore.AccessToken;
|
||||||
|
|
||||||
|
// TokenStore가 비어있으면 localStorage에서 복원 (페이지 리로드 후)
|
||||||
|
if (string.IsNullOrEmpty(accessToken))
|
||||||
|
{
|
||||||
|
accessToken = await _localStorage.GetItemAsStringAsync("accessToken");
|
||||||
|
if (!string.IsNullOrEmpty(accessToken))
|
||||||
|
{
|
||||||
|
var refreshToken = await _localStorage.GetItemAsStringAsync("refreshToken");
|
||||||
|
var ticksStr = await _localStorage.GetItemAsStringAsync("tokenExpiry");
|
||||||
|
if (long.TryParse(ticksStr, out var ticks))
|
||||||
|
{
|
||||||
|
_tokenStore.AccessToken = accessToken;
|
||||||
|
_tokenStore.RefreshToken = refreshToken;
|
||||||
|
_tokenStore.TokenExpiryTicks = ticks;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
if (string.IsNullOrEmpty(accessToken))
|
if (string.IsNullOrEmpty(accessToken))
|
||||||
{
|
{
|
||||||
return new AuthenticationState(new ClaimsPrincipal(new ClaimsIdentity()));
|
return new AuthenticationState(new ClaimsPrincipal(new ClaimsIdentity()));
|
||||||
}
|
}
|
||||||
|
|
||||||
if (IsTokenExpired(accessToken))
|
if (_tokenStore.IsAccessTokenExpired())
|
||||||
{
|
{
|
||||||
_logger.LogWarning("Access token 만료됨");
|
_logger.LogWarning("Access token 만료됨");
|
||||||
await LogoutAsync();
|
await LogoutAsync();
|
||||||
@@ -53,18 +76,31 @@ public class CustomAuthenticationStateProvider : AuthenticationStateProvider
|
|||||||
|
|
||||||
public async Task LoginAsync(string accessToken, string refreshToken, int expiresIn)
|
public async Task LoginAsync(string accessToken, string refreshToken, int expiresIn)
|
||||||
{
|
{
|
||||||
|
var tokenExpiryTicks = DateTime.UtcNow.AddSeconds(expiresIn).Ticks;
|
||||||
|
|
||||||
|
// TokenStore에 저장 (DelegatingHandler에서 사용)
|
||||||
|
_tokenStore.AccessToken = accessToken;
|
||||||
|
_tokenStore.RefreshToken = refreshToken;
|
||||||
|
_tokenStore.TokenExpiryTicks = tokenExpiryTicks;
|
||||||
|
|
||||||
|
// localStorage에도 저장 (페이지 리로드 후 복원)
|
||||||
await _localStorage.SetItemAsStringAsync("accessToken", accessToken);
|
await _localStorage.SetItemAsStringAsync("accessToken", accessToken);
|
||||||
await _localStorage.SetItemAsStringAsync("refreshToken", refreshToken);
|
await _localStorage.SetItemAsStringAsync("refreshToken", refreshToken);
|
||||||
await _localStorage.SetItemAsStringAsync("tokenExpiry",
|
await _localStorage.SetItemAsStringAsync("tokenExpiry", tokenExpiryTicks.ToString());
|
||||||
DateTime.UtcNow.AddSeconds(expiresIn).Ticks.ToString());
|
|
||||||
NotifyAuthenticationStateChanged(GetAuthenticationStateAsync());
|
NotifyAuthenticationStateChanged(GetAuthenticationStateAsync());
|
||||||
}
|
}
|
||||||
|
|
||||||
public async Task LogoutAsync()
|
public async Task LogoutAsync()
|
||||||
{
|
{
|
||||||
|
// TokenStore 초기화
|
||||||
|
_tokenStore.Clear();
|
||||||
|
|
||||||
|
// localStorage 초기화
|
||||||
await _localStorage.RemoveItemAsync("accessToken");
|
await _localStorage.RemoveItemAsync("accessToken");
|
||||||
await _localStorage.RemoveItemAsync("refreshToken");
|
await _localStorage.RemoveItemAsync("refreshToken");
|
||||||
await _localStorage.RemoveItemAsync("tokenExpiry");
|
await _localStorage.RemoveItemAsync("tokenExpiry");
|
||||||
|
|
||||||
NotifyAuthenticationStateChanged(GetAuthenticationStateAsync());
|
NotifyAuthenticationStateChanged(GetAuthenticationStateAsync());
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -0,0 +1,39 @@
|
|||||||
|
namespace TaxBaik.Web.Services;
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Scoped in-memory token store for Blazor Server.
|
||||||
|
/// SOLID: Single Responsibility - Token lifecycle management
|
||||||
|
/// Avoids JS interop from DelegatingHandler (which runs on non-circuit thread)
|
||||||
|
/// </summary>
|
||||||
|
public interface ITokenStore
|
||||||
|
{
|
||||||
|
string? AccessToken { get; set; }
|
||||||
|
string? RefreshToken { get; set; }
|
||||||
|
long? TokenExpiryTicks { get; set; }
|
||||||
|
|
||||||
|
bool IsAccessTokenExpired();
|
||||||
|
void Clear();
|
||||||
|
}
|
||||||
|
|
||||||
|
public class TokenStore : ITokenStore
|
||||||
|
{
|
||||||
|
public string? AccessToken { get; set; }
|
||||||
|
public string? RefreshToken { get; set; }
|
||||||
|
public long? TokenExpiryTicks { get; set; }
|
||||||
|
|
||||||
|
public bool IsAccessTokenExpired()
|
||||||
|
{
|
||||||
|
if (TokenExpiryTicks == null)
|
||||||
|
return true;
|
||||||
|
|
||||||
|
var expiryTime = new DateTime(TokenExpiryTicks.Value, DateTimeKind.Utc);
|
||||||
|
return expiryTime <= DateTime.UtcNow;
|
||||||
|
}
|
||||||
|
|
||||||
|
public void Clear()
|
||||||
|
{
|
||||||
|
AccessToken = null;
|
||||||
|
RefreshToken = null;
|
||||||
|
TokenExpiryTicks = null;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -10,12 +10,12 @@ using System.Text.Json;
|
|||||||
/// </summary>
|
/// </summary>
|
||||||
public class TokenRefreshHandler : DelegatingHandler
|
public class TokenRefreshHandler : DelegatingHandler
|
||||||
{
|
{
|
||||||
private readonly ILocalStorageService _localStorage;
|
private readonly ITokenStore _tokenStore;
|
||||||
private readonly ILogger<TokenRefreshHandler> _logger;
|
private readonly ILogger<TokenRefreshHandler> _logger;
|
||||||
|
|
||||||
public TokenRefreshHandler(ILocalStorageService localStorage, ILogger<TokenRefreshHandler> logger)
|
public TokenRefreshHandler(ITokenStore tokenStore, ILogger<TokenRefreshHandler> logger)
|
||||||
{
|
{
|
||||||
_localStorage = localStorage;
|
_tokenStore = tokenStore;
|
||||||
_logger = logger;
|
_logger = logger;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -24,10 +24,9 @@ public class TokenRefreshHandler : DelegatingHandler
|
|||||||
CancellationToken cancellationToken)
|
CancellationToken cancellationToken)
|
||||||
{
|
{
|
||||||
// 요청에 access token 추가
|
// 요청에 access token 추가
|
||||||
var accessToken = await _localStorage.GetItemAsStringAsync("accessToken");
|
if (!string.IsNullOrEmpty(_tokenStore.AccessToken))
|
||||||
if (!string.IsNullOrEmpty(accessToken))
|
|
||||||
{
|
{
|
||||||
request.Headers.Authorization = new("Bearer", accessToken);
|
request.Headers.Authorization = new("Bearer", _tokenStore.AccessToken);
|
||||||
}
|
}
|
||||||
|
|
||||||
var response = await base.SendAsync(request, cancellationToken);
|
var response = await base.SendAsync(request, cancellationToken);
|
||||||
@@ -35,17 +34,15 @@ public class TokenRefreshHandler : DelegatingHandler
|
|||||||
// 401 응답이면 토큰 갱신 시도
|
// 401 응답이면 토큰 갱신 시도
|
||||||
if (response.StatusCode == HttpStatusCode.Unauthorized)
|
if (response.StatusCode == HttpStatusCode.Unauthorized)
|
||||||
{
|
{
|
||||||
var refreshToken = await _localStorage.GetItemAsStringAsync("refreshToken");
|
if (!string.IsNullOrEmpty(_tokenStore.RefreshToken))
|
||||||
if (!string.IsNullOrEmpty(refreshToken))
|
|
||||||
{
|
{
|
||||||
var newTokenPair = await RefreshTokenAsync(refreshToken, request, cancellationToken);
|
var newTokenPair = await RefreshTokenAsync(_tokenStore.RefreshToken, request, cancellationToken);
|
||||||
if (newTokenPair != null)
|
if (newTokenPair != null)
|
||||||
{
|
{
|
||||||
// 토큰 저장
|
// TokenStore에 토큰 저장
|
||||||
await _localStorage.SetItemAsStringAsync("accessToken", newTokenPair.AccessToken);
|
_tokenStore.AccessToken = newTokenPair.AccessToken;
|
||||||
await _localStorage.SetItemAsStringAsync("refreshToken", newTokenPair.RefreshToken);
|
_tokenStore.RefreshToken = newTokenPair.RefreshToken;
|
||||||
await _localStorage.SetItemAsStringAsync("tokenExpiry",
|
_tokenStore.TokenExpiryTicks = DateTime.UtcNow.AddSeconds(newTokenPair.ExpiresIn).Ticks;
|
||||||
DateTime.UtcNow.AddSeconds(newTokenPair.ExpiresIn).Ticks.ToString());
|
|
||||||
|
|
||||||
// 새 토큰으로 재요청
|
// 새 토큰으로 재요청
|
||||||
request.Headers.Authorization = new("Bearer", newTokenPair.AccessToken);
|
request.Headers.Authorization = new("Bearer", newTokenPair.AccessToken);
|
||||||
@@ -54,9 +51,7 @@ public class TokenRefreshHandler : DelegatingHandler
|
|||||||
else
|
else
|
||||||
{
|
{
|
||||||
_logger.LogWarning("토큰 갱신 실패 - 로그아웃");
|
_logger.LogWarning("토큰 갱신 실패 - 로그아웃");
|
||||||
await _localStorage.RemoveItemAsync("accessToken");
|
_tokenStore.Clear();
|
||||||
await _localStorage.RemoveItemAsync("refreshToken");
|
|
||||||
await _localStorage.RemoveItemAsync("tokenExpiry");
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
Reference in New Issue
Block a user