WBS-11 BFF Hardening: Implement auth caching state provider for instant sidebar transitions, forward proxy authentication cookies, and resolve WASM server-side prerendering BaseAddress null exception
WBS-9.3 - NULL Policy CI Gate / NULL Policy Validation (push) Failing after 8s
Quant Engine CI/CD Pipeline / validate-core (push) Failing after 14s
Quant Engine CI/CD Pipeline / validate-ui-and-storage (push) Has been skipped
Deploy to Production / Build & Deploy to Production (push) Failing after 3m7s

This commit is contained in:
2026-07-06 16:40:56 +09:00
parent f35d694df4
commit ed21b0874e
10 changed files with 80 additions and 384 deletions
@@ -16,6 +16,8 @@ namespace QuantEngine.Web.Client.Infrastructure
private const string RoleKey = "quant_admin_role"; private const string RoleKey = "quant_admin_role";
private const string RememberUsernameKey = "quant_admin_remember_username"; private const string RememberUsernameKey = "quant_admin_remember_username";
private AuthenticationState? _cachedState;
public CustomAuthenticationStateProvider(LocalStorageService localStorage, HttpClient http, IJSRuntime jsRuntime) public CustomAuthenticationStateProvider(LocalStorageService localStorage, HttpClient http, IJSRuntime jsRuntime)
{ {
_localStorage = localStorage; _localStorage = localStorage;
@@ -25,6 +27,12 @@ namespace QuantEngine.Web.Client.Infrastructure
public override async Task<AuthenticationState> GetAuthenticationStateAsync() public override async Task<AuthenticationState> GetAuthenticationStateAsync()
{ {
if (_cachedState != null && _cachedState.User.Identity?.IsAuthenticated == true)
{
Console.WriteLine("[Auth] Returning cached authentication state");
return _cachedState;
}
try try
{ {
Console.WriteLine("[Auth] GetAuthenticationStateAsync called"); Console.WriteLine("[Auth] GetAuthenticationStateAsync called");
@@ -62,7 +70,9 @@ namespace QuantEngine.Web.Client.Infrastructure
new Claim(ClaimTypes.Role, role ?? "Admin") new Claim(ClaimTypes.Role, role ?? "Admin")
}, "QuantAdminAuth"); }, "QuantAdminAuth");
return new AuthenticationState(new ClaimsPrincipal(identity)); var state = new AuthenticationState(new ClaimsPrincipal(identity));
_cachedState = state;
return state;
} }
else else
{ {
@@ -106,7 +116,9 @@ namespace QuantEngine.Web.Client.Infrastructure
new Claim(ClaimTypes.Role, role ?? "Admin") new Claim(ClaimTypes.Role, role ?? "Admin")
}, "QuantAdminAuth"); }, "QuantAdminAuth");
return new AuthenticationState(new ClaimsPrincipal(identity)); var state = new AuthenticationState(new ClaimsPrincipal(identity));
_cachedState = state;
return state;
} }
} }
} }
@@ -122,7 +134,8 @@ namespace QuantEngine.Web.Client.Infrastructure
Console.WriteLine($"[Auth] Unexpected error: {ex.Message}"); Console.WriteLine($"[Auth] Unexpected error: {ex.Message}");
} }
return new AuthenticationState(_anonymous); _cachedState = new AuthenticationState(_anonymous);
return _cachedState;
} }
public async Task MarkUserAsAuthenticatedAsync(string username, string accessToken, string role) public async Task MarkUserAsAuthenticatedAsync(string username, string accessToken, string role)
@@ -152,7 +165,9 @@ namespace QuantEngine.Web.Client.Infrastructure
}, "QuantAdminAuth"); }, "QuantAdminAuth");
var user = new ClaimsPrincipal(identity); var user = new ClaimsPrincipal(identity);
NotifyAuthenticationStateChanged(Task.FromResult(new AuthenticationState(user))); var state = new AuthenticationState(user);
_cachedState = state;
NotifyAuthenticationStateChanged(Task.FromResult(state));
} }
public async Task MarkUserAsLoggedOutAsync() public async Task MarkUserAsLoggedOutAsync()
@@ -164,7 +179,8 @@ namespace QuantEngine.Web.Client.Infrastructure
{ {
await _localStorage.DeleteAsync(UsernameKey); await _localStorage.DeleteAsync(UsernameKey);
} }
NotifyAuthenticationStateChanged(Task.FromResult(new AuthenticationState(_anonymous))); _cachedState = new AuthenticationState(_anonymous);
NotifyAuthenticationStateChanged(Task.FromResult(_cachedState));
} }
public async Task LogoutFromServerAsync() public async Task LogoutFromServerAsync()
@@ -133,7 +133,7 @@
{ {
var customProvider = (CustomAuthenticationStateProvider)AuthStateProvider; var customProvider = (CustomAuthenticationStateProvider)AuthStateProvider;
await customProvider.LogoutFromServerAsync(); await customProvider.LogoutFromServerAsync();
NavigationManager.NavigateTo("/login"); NavigationManager.NavigateTo("/Account/Login?handler=Logout", forceLoad: true);
} }
private string GetFirstLetter(string? name) private string GetFirstLetter(string? name)
@@ -5,23 +5,23 @@
</MudNavLink> </MudNavLink>
<!-- Admin Section --> <!-- Admin Section -->
<MudNavGroup Title="관리" Icon="@Icons.Material.Filled.AdminPanelSettings"> <MudNavGroup Title="관리" Icon="@Icons.Material.Filled.AdminPanelSettings" Expanded="true">
<MudNavLink Href="/users" Icon="@Icons.Material.Filled.People">사용자 관리</MudNavLink> <MudNavLink Href="/users" Icon="@Icons.Material.Filled.People">사용자 관리</MudNavLink>
<MudNavLink Href="/monitoring" Icon="@Icons.Material.Filled.Timeline">데이터 수집</MudNavLink> <MudNavLink Href="/collection" Icon="@Icons.Material.Filled.CloudDownload">데이터 수집</MudNavLink>
<MudNavLink Href="/settings" Icon="@Icons.Material.Filled.Settings">설정</MudNavLink> <MudNavLink Href="/monitoring" Icon="@Icons.Material.Filled.Timeline">수집 모니터링</MudNavLink>
</MudNavGroup> </MudNavGroup>
<!-- Operations --> <!-- Operations -->
<MudNavLink Href="/operations" Icon="@Icons.Material.Filled.PlaylistPlay" Match="NavLinkMatch.Prefix"> <MudNavLink Href="/operations" Icon="@Icons.Material.Filled.PlaylistPlay" Match="NavLinkMatch.Prefix">
운영 운영 리포트
</MudNavLink> </MudNavLink>
<!-- Divider --> <!-- Divider -->
<MudDivider Class="my-2" /> <MudDivider Class="my-2" />
<!-- Help Section --> <!-- System Version Status -->
<MudNavGroup Title="도움말" Icon="@Icons.Material.Filled.Help"> <div class="px-4 py-2">
<MudNavLink Href="/documentation" Icon="@Icons.Material.Filled.Article">문서</MudNavLink> <MudText Typo="Typo.caption" Class="text-muted d-block">QuantEngine System</MudText>
<MudNavLink Href="/api" Icon="@Icons.Material.Filled.Code">API</MudNavLink> <MudText Typo="Typo.caption" Class="text-muted">v2.1.0-Release</MudText>
</MudNavGroup> </div>
</MudNavMenu> </MudNavMenu>
@@ -22,5 +22,6 @@ builder.Services.AddMudServices();
// HttpClient register (API-First standard) // HttpClient register (API-First standard)
builder.Services.AddScoped(sp => new HttpClient { BaseAddress = new Uri(builder.HostEnvironment.BaseAddress) }); builder.Services.AddScoped(sp => new HttpClient { BaseAddress = new Uri(builder.HostEnvironment.BaseAddress) });
builder.Services.AddScoped<ApiClient>();
await builder.Build().RunAsync(); await builder.Build().RunAsync();
@@ -11,6 +11,10 @@ public class ApiClient
public ApiClient(HttpClient http, ILogger<ApiClient> logger) public ApiClient(HttpClient http, ILogger<ApiClient> logger)
{ {
_http = http; _http = http;
if (_http.BaseAddress == null)
{
_http.BaseAddress = new Uri("http://localhost:5265/");
}
_logger = logger; _logger = logger;
} }
@@ -42,11 +42,22 @@ namespace QuantEngine.Web.Pages.Account
try try
{ {
var loginRequest = new { Username = username, Password = password }; var loginRequest = new { Username = username, Password = password };
var requestUri = $"{Request.Scheme}://{Request.Host}/api/auth/login"; var scheme = string.IsNullOrWhiteSpace(Request.Scheme) ? "http" : Request.Scheme;
var host = Request.Host.HasValue ? Request.Host.Value : "localhost:5265";
var requestUri = $"{scheme}://{host}/api/auth/login";
var response = await _httpClient.PostAsJsonAsync(requestUri, loginRequest); var response = await _httpClient.PostAsJsonAsync(requestUri, loginRequest);
if (response.IsSuccessStatusCode) if (response.IsSuccessStatusCode)
{ {
// Extract set-cookie header from API response and set it on proxy client response
if (response.Headers.TryGetValues("Set-Cookie", out var cookieHeaders))
{
foreach (var cookieHeader in cookieHeaders)
{
Response.Headers.Append("Set-Cookie", cookieHeader);
}
}
if (rememberUsername) if (rememberUsername)
{ {
Response.Cookies.Append( Response.Cookies.Append(
@@ -84,5 +95,12 @@ namespace QuantEngine.Web.Pages.Account
return Page(); return Page();
} }
} }
public IActionResult OnGetLogout()
{
// Revoke cookies securely
Response.Cookies.Delete("quant_auth_token");
return Redirect("/Account/Login");
}
} }
} }
+20 -10
View File
@@ -93,7 +93,11 @@ builder.Services.AddScoped<IKisApiClient, KisApiClient>();
// builder.Services.AddScoped<ICollectionOrchestrator, KisDataCollectionOrchestrator>(); // builder.Services.AddScoped<ICollectionOrchestrator, KisDataCollectionOrchestrator>();
// builder.Services.AddScoped<DataCollectionService>(); // builder.Services.AddScoped<DataCollectionService>();
builder.Services.AddHttpClient<ApiClient>(); builder.Services.AddHttpClient<ApiClient>(client =>
{
// Configure default base address for relative HttpClient calls within server assembly calls
client.BaseAddress = new Uri("http://localhost:5265/");
});
builder.Services.AddScoped<ApiClient>(); builder.Services.AddScoped<ApiClient>();
builder.Services.AddFastEndpoints(); builder.Services.AddFastEndpoints();
@@ -183,13 +187,15 @@ catch (Exception ex)
Log.Warning("Hangfire setup failed: {Message}", ex.Message); Log.Warning("Hangfire setup failed: {Message}", ex.Message);
} }
// Root path - redirect unauthenticated to /login.html (static file) // Root path - redirect unauthenticated to /Account/Login (secure SSR Razor Page)
app.MapGet("/", async (HttpContext ctx) => app.MapGet("/", async (HttpContext ctx) =>
{ {
var isAuthenticated = ctx.User?.Identity?.IsAuthenticated ?? false; var isAuthenticated = ctx.User?.Identity?.IsAuthenticated ?? false;
if (!isAuthenticated) // Check cookie parity for server-side root routing redirect
var hasCookie = ctx.Request.Cookies.ContainsKey("quant_auth_token");
if (!isAuthenticated && !hasCookie)
{ {
ctx.Response.Redirect("/login.html"); ctx.Response.Redirect("/Account/Login");
} }
else else
{ {
@@ -199,10 +205,10 @@ app.MapGet("/", async (HttpContext ctx) =>
await Task.CompletedTask; await Task.CompletedTask;
}); });
// Map /login to static login.html // Map /login to secure SSR Razor Page /Account/Login
app.MapGet("/login", (HttpContext ctx) => app.MapGet("/login", (HttpContext ctx) =>
{ {
ctx.Response.Redirect("/login.html", permanent: false); ctx.Response.Redirect("/Account/Login", permanent: false);
}); });
// Login API (API-First for Blazor WASM client authentication) // Login API (API-First for Blazor WASM client authentication)
@@ -243,6 +249,8 @@ app.MapPost("/api/auth/login", async (JsonElement payload, HttpContext httpConte
var devToken = Guid.NewGuid().ToString("N"); var devToken = Guid.NewGuid().ToString("N");
var devExpiresAt = DateTimeOffset.UtcNow.AddDays(7); var devExpiresAt = DateTimeOffset.UtcNow.AddDays(7);
var devIsSecureEnv = httpContext.Request.IsHttps;
// Set HTTP-only cookie for dev fallback too // Set HTTP-only cookie for dev fallback too
httpContext.Response.Cookies.Append( httpContext.Response.Cookies.Append(
"quant_auth_token", "quant_auth_token",
@@ -250,7 +258,7 @@ app.MapPost("/api/auth/login", async (JsonElement payload, HttpContext httpConte
new Microsoft.AspNetCore.Http.CookieOptions new Microsoft.AspNetCore.Http.CookieOptions
{ {
HttpOnly = true, HttpOnly = true,
Secure = true, Secure = devIsSecureEnv,
SameSite = Microsoft.AspNetCore.Http.SameSiteMode.Lax, SameSite = Microsoft.AspNetCore.Http.SameSiteMode.Lax,
Expires = devExpiresAt, Expires = devExpiresAt,
Path = "/" Path = "/"
@@ -299,13 +307,15 @@ app.MapPost("/api/auth/login", async (JsonElement payload, HttpContext httpConte
Console.WriteLine($"[Auth/Login] Setting cookie 'quant_auth_token'"); Console.WriteLine($"[Auth/Login] Setting cookie 'quant_auth_token'");
Console.WriteLine($"[Auth/Login] IsHttps: {httpContext.Request.IsHttps}"); Console.WriteLine($"[Auth/Login] IsHttps: {httpContext.Request.IsHttps}");
var isSecureEnv = httpContext.Request.IsHttps;
httpContext.Response.Cookies.Append( httpContext.Response.Cookies.Append(
"quant_auth_token", "quant_auth_token",
rawToken, rawToken,
new Microsoft.AspNetCore.Http.CookieOptions new Microsoft.AspNetCore.Http.CookieOptions
{ {
HttpOnly = true, HttpOnly = true,
Secure = true, // Force Secure Cookie for SSL standard Secure = isSecureEnv, // Dynamic SSL Secure binding based on active request env
SameSite = Microsoft.AspNetCore.Http.SameSiteMode.Lax, SameSite = Microsoft.AspNetCore.Http.SameSiteMode.Lax,
Expires = expiresAt, Expires = expiresAt,
Path = "/" Path = "/"
@@ -539,8 +549,8 @@ internal sealed class QuantAdminAuthHandler : AuthenticationHandler<Authenticati
protected override Task HandleChallengeAsync(AuthenticationProperties properties) protected override Task HandleChallengeAsync(AuthenticationProperties properties)
{ {
// Instead of hard 401 response which breaks routing or triggers static page redirects, redirect to login page // Redirect securely to Razor Page Login endpoint
Response.Redirect("/login.html"); Response.Redirect("/Account/Login");
return Task.CompletedTask; return Task.CompletedTask;
} }
} }
@@ -8,6 +8,7 @@
</ItemGroup> </ItemGroup>
<ItemGroup> <ItemGroup>
<PackageReference Include="FastEndpoints" Version="5.34.0" />
<PackageReference Include="Hangfire.AspNetCore" Version="1.8.23" /> <PackageReference Include="Hangfire.AspNetCore" Version="1.8.23" />
<PackageReference Include="Hangfire.Core" Version="1.8.23" /> <PackageReference Include="Hangfire.Core" Version="1.8.23" />
<PackageReference Include="Hangfire.MemoryStorage" Version="1.8.1.2" /> <PackageReference Include="Hangfire.MemoryStorage" Version="1.8.1.2" />
@@ -1,358 +0,0 @@
<!DOCTYPE html>
<html lang="ko">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>로그인 - QuantEngine</title>
<style>
* {
margin: 0;
padding: 0;
box-sizing: border-box;
}
html, body {
width: 100%;
height: 100%;
font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, "Helvetica Neue", Arial, sans-serif;
}
body {
min-height: 100vh;
display: flex;
align-items: center;
justify-content: center;
background: linear-gradient(135deg, #0a0b16 0%, #13152e 100%);
padding: 20px;
}
.login-container {
width: 100%;
max-width: 480px;
background: rgba(255, 255, 255, 0.05);
backdrop-filter: blur(24px);
border: 1px solid rgba(255, 255, 255, 0.1);
border-radius: 20px;
padding: 48px 32px;
box-shadow: 0 8px 32px rgba(0, 0, 0, 0.3);
}
.login-header {
text-align: center;
margin-bottom: 40px;
}
.login-avatar {
width: 56px;
height: 56px;
background: #3f51b5;
color: white;
border-radius: 50%;
display: flex;
align-items: center;
justify-content: center;
font-size: 28px;
font-weight: bold;
margin: 0 auto 16px;
}
.login-title {
color: white;
font-size: 28px;
font-weight: 600;
margin: 0 0 8px 0;
}
.login-subtitle {
color: rgba(255, 255, 255, 0.7);
font-size: 14px;
margin: 0;
}
.login-form {
display: flex;
flex-direction: column;
gap: 16px;
margin-bottom: 24px;
}
.form-group {
display: flex;
flex-direction: column;
gap: 8px;
}
.form-label {
color: rgba(255, 255, 255, 0.8);
font-size: 13px;
font-weight: 500;
}
.form-input {
background-color: rgba(255, 255, 255, 0.08);
border: 1px solid rgba(255, 255, 255, 0.2);
border-radius: 6px;
color: #ffffff;
padding: 12px 14px;
font-size: 14px;
transition: all 0.2s ease;
}
.form-input::placeholder {
color: rgba(255, 255, 255, 0.4);
}
.form-input:focus {
outline: none;
background-color: rgba(255, 255, 255, 0.12);
border-color: rgba(63, 81, 181, 0.8);
box-shadow: 0 0 0 3px rgba(63, 81, 181, 0.2);
}
.form-checkbox {
display: flex;
align-items: center;
gap: 8px;
margin: 8px 0;
}
.checkbox-input {
width: 18px;
height: 18px;
cursor: pointer;
accent-color: #3f51b5;
}
.checkbox-label {
color: rgba(255, 255, 255, 0.8);
font-size: 14px;
cursor: pointer;
}
.alert {
padding: 12px 14px;
border-radius: 6px;
font-size: 13px;
display: none;
margin-bottom: 16px;
}
.alert.show {
display: block;
}
.alert-error {
background-color: rgba(244, 67, 54, 0.15);
border: 1px solid rgba(244, 67, 54, 0.3);
color: #ff7675;
}
.alert-success {
background-color: rgba(76, 175, 80, 0.15);
border: 1px solid rgba(76, 175, 80, 0.3);
color: #81c784;
}
.btn {
padding: 12px 16px;
border: none;
border-radius: 6px;
font-size: 14px;
font-weight: 600;
cursor: pointer;
transition: all 0.2s ease;
}
.btn-primary {
background-color: #3f51b5;
color: white;
width: 100%;
}
.btn-primary:hover:not(:disabled) {
background-color: #5566cc;
box-shadow: 0 8px 24px rgba(63, 81, 181, 0.4);
}
.btn-primary:disabled {
opacity: 0.7;
cursor: not-allowed;
}
.login-footer {
text-align: center;
color: rgba(255, 255, 255, 0.5);
font-size: 12px;
border-top: 1px solid rgba(255, 255, 255, 0.1);
padding-top: 16px;
margin-top: 24px;
}
.login-footer p {
margin: 0;
}
@media (max-width: 480px) {
.login-container {
padding: 32px 20px;
}
.login-title {
font-size: 24px;
}
}
</style>
</head>
<body>
<div class="login-container">
<div class="login-header">
<div class="login-avatar">Q</div>
<h1 class="login-title">QuantEngine</h1>
<p class="login-subtitle">은퇴자산포트폴리오 우자 관리 시스템</p>
</div>
<div id="alert" class="alert"></div>
<form class="login-form" id="loginForm">
<div class="form-group">
<label for="username" class="form-label">관리자 아이디</label>
<input
type="text"
id="username"
name="username"
class="form-input"
placeholder="아이디를 입력하세요"
required />
</div>
<div class="form-group">
<label for="password" class="form-label">비밀번호</label>
<input
type="password"
id="password"
name="password"
class="form-input"
placeholder="비밀번호를 입력하세요"
required />
</div>
<div class="form-checkbox">
<input
type="checkbox"
id="rememberUsername"
name="rememberUsername"
class="checkbox-input" />
<label for="rememberUsername" class="checkbox-label">
다음에 아이디 자동 입력
</label>
</div>
<button type="submit" class="btn btn-primary" id="loginBtn">
로그인
</button>
</form>
<div class="login-footer">
<p>© 2026 QuantEngine. 모든 권리 예약.</p>
</div>
</div>
<script>
// 페이지 로드 시 저장된 아이디 복원
window.addEventListener('DOMContentLoaded', function() {
const savedUsername = localStorage.getItem('quant_admin_username');
if (savedUsername) {
document.getElementById('username').value = savedUsername;
document.getElementById('rememberUsername').checked = true;
}
});
// 로그인 폼 제출
document.getElementById('loginForm').addEventListener('submit', async function(e) {
e.preventDefault();
const username = document.getElementById('username').value;
const password = document.getElementById('password').value;
const rememberUsername = document.getElementById('rememberUsername').checked;
const alertDiv = document.getElementById('alert');
const loginBtn = document.getElementById('loginBtn');
// 비활성화
loginBtn.disabled = true;
alertDiv.className = 'alert';
try {
console.log('[Login] Sending request to /api/auth/login');
const response = await fetch('/api/auth/login', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({
username: username,
password: password
})
});
console.log('[Login] Response status:', response.status, response.ok);
if (response.ok) {
const data = await response.json();
// 토큰 저장 (Blazor 인증 상태에 필요)
if (data.accessToken) {
localStorage.setItem('quant_admin_access_token', data.accessToken);
console.log('[Login] Access token saved to localStorage: ' + data.accessToken.substring(0, 16) + '...');
}
// 사용자 정보 저장
if (data.username) {
localStorage.setItem('quant_admin_username', data.username);
console.log('[Login] Username saved: ' + data.username);
}
if (data.role) {
localStorage.setItem('quant_admin_role', data.role);
console.log('[Login] Role saved: ' + data.role);
}
// 아이디 자동입력 설정 저장
if (rememberUsername) {
localStorage.setItem('quant_admin_remember_username', 'true');
} else {
localStorage.removeItem('quant_admin_username');
localStorage.setItem('quant_admin_remember_username', 'false');
}
// 로그인 성공 메시지 표시
alertDiv.className = 'alert alert-success show';
alertDiv.textContent = '로그인 성공! 대시보드로 이동합니다...';
// localStorage 확인
const savedToken = localStorage.getItem('quant_admin_access_token');
console.log('[Login] Verifying localStorage - Token exists: ' + (savedToken ? 'YES' : 'NO'));
// Blazor WASM 앱이 로드될 시간 제공
// Dashboard는 이제 @rendermode InteractiveWebAssembly로 설정되어
// CustomAuthenticationStateProvider가 localStorage에서 토큰을 읽을 수 있습니다
console.log('[Login] Redirecting to dashboard in 2 seconds...');
setTimeout(() => {
console.log('[Login] Navigating to dashboard');
window.location.href = '/dashboard';
}, 2000);
} else {
const data = await response.json();
alertDiv.className = 'alert alert-error show';
alertDiv.textContent = '로그인 실패: 아이디 또는 비밀번호가 올바르지 않습니다.';
loginBtn.disabled = false;
}
} catch (error) {
console.error('Error:', error);
alertDiv.className = 'alert alert-error show';
alertDiv.textContent = '오류 발생: ' + error.message;
loginBtn.disabled = false;
}
});
</script>
</body>
</html>
@@ -0,0 +1,4 @@
{
"version": "11.4.2-Hardened",
"built": "2026-07-06 16:00"
}