fix: implement Blazor-native login form to properly update authentication state
TaxBaik CI/CD / build-and-deploy (push) Successful in 2m26s
TaxBaik CI/CD / build-and-deploy (push) Successful in 2m26s
Problem: JavaScript login form saved tokens to localStorage but didn't notify CustomAuthenticationStateProvider, causing [Authorize] pages to remain in 'loading' state indefinitely. The provider only reads tokens when: 1. GetAuthenticationStateAsync() is called (page load) 2. NotifyAuthenticationStateChanged() is triggered (UI updates) But JavaScript login didn't trigger either, leaving the authentication state stale. Solution: Convert AdminLoginForm from HTML+JavaScript to pure Blazor component. Now the login flow is: 1. User enters credentials in Blazor form 2. HttpClient POST to /api/auth/login 3. Save tokens to localStorage 4. Call CustomAuthenticationStateProvider.LoginAsync() directly 5. Blazor detects auth state change and re-evaluates [Authorize] pages 6. Dashboard [Authorize] page renders successfully Result: Immediate authentication state update, no loading timeout on protected pages. Co-Authored-By: Claude Haiku 4.5 <noreply@anthropic.com>
This commit is contained in:
@@ -1,47 +1,57 @@
|
||||
@using System.Text.Json
|
||||
@inject ILocalStorageService LocalStorageService
|
||||
@inject IJSRuntime Js
|
||||
@inject NavigationManager Navigation
|
||||
@inject ISnackbar Snackbar
|
||||
@inject HttpClient Http
|
||||
@inject AuthenticationStateProvider AuthStateProvider
|
||||
|
||||
<MudContainer MaxWidth="MaxWidth.Small" Class="admin-login-page d-flex align-center justify-center" Style="min-height: 100vh;">
|
||||
<MudPaper Class="pa-8" Elevation="3" Style="width: 100%; max-width: 400px;">
|
||||
<MudText Typo="Typo.h4" Class="mb-6 text-center">관리자 로그인</MudText>
|
||||
|
||||
<form id="admin-login-form">
|
||||
<input class="mud-input mud-input-outlined mud-input-root mud-input-root-adorned-start mb-4"
|
||||
style="width: 100%; min-height: 56px; padding: 16px 14px;"
|
||||
placeholder="사용자명"
|
||||
autocomplete="username"
|
||||
name="username"
|
||||
value="@rememberedUsername" />
|
||||
<MudForm @ref="form" OnSubmit="HandleLogin">
|
||||
<MudTextField @bind-Value="username"
|
||||
Label="사용자명"
|
||||
Placeholder="사용자명"
|
||||
Variant="Variant.Outlined"
|
||||
Class="mb-4"
|
||||
Required="true"
|
||||
Disabled="@isLoggingIn"
|
||||
InputType="InputType.Text"
|
||||
Autocomplete="username" />
|
||||
|
||||
<input type="password"
|
||||
class="mud-input mud-input-outlined mud-input-root mud-input-root-adorned-start mb-4"
|
||||
style="width: 100%; min-height: 56px; padding: 16px 14px;"
|
||||
placeholder="비밀번호"
|
||||
autocomplete="current-password"
|
||||
name="password" />
|
||||
<MudTextField @bind-Value="password"
|
||||
Label="비밀번호"
|
||||
Placeholder="비밀번호"
|
||||
Variant="Variant.Outlined"
|
||||
Class="mb-4"
|
||||
Required="true"
|
||||
Disabled="@isLoggingIn"
|
||||
InputType="InputType.Password"
|
||||
Autocomplete="current-password" />
|
||||
|
||||
<div class="mb-4">
|
||||
<input class="mud-checkbox" type="checkbox" name="rememberMe" />
|
||||
<label style="margin-left: 8px; cursor: pointer;">아이디 저장</label>
|
||||
<MudCheckBox @bind-Checked="rememberMe" Label="아이디 저장" Disabled="@isLoggingIn" />
|
||||
</div>
|
||||
|
||||
<div class="mud-alert mud-alert-filled-error mb-4 login-error-message" style="display:none;">로그인 중 오류가 발생했습니다.</div>
|
||||
|
||||
<button type="submit"
|
||||
id="admin-login-submit"
|
||||
disabled="@(!isReady)"
|
||||
class="mud-button-root mud-button mud-button-filled mud-button-filled-primary mud-elevation-0"
|
||||
style="width: 100%; min-height: 52px; border: 0; border-radius: 4px; color: white;">
|
||||
<span>@(isReady ? "로그인" : "준비 중...")</span>
|
||||
</button>
|
||||
</form>
|
||||
<MudButton ButtonType="ButtonType.Submit"
|
||||
Variant="Variant.Filled"
|
||||
Color="Color.Primary"
|
||||
FullWidth="true"
|
||||
Disabled="@isLoggingIn"
|
||||
Class="mud-elevation-0">
|
||||
@(isLoggingIn ? "로그인 중..." : "로그인")
|
||||
</MudButton>
|
||||
</MudForm>
|
||||
</MudPaper>
|
||||
</MudContainer>
|
||||
|
||||
@code {
|
||||
private string rememberedUsername = "";
|
||||
private bool isRememberChecked = false;
|
||||
private bool isReady;
|
||||
private MudForm? form;
|
||||
private string username = "";
|
||||
private string password = "";
|
||||
private bool rememberMe = false;
|
||||
private bool isLoggingIn = false;
|
||||
private const string RememberedUsernameKey = "admin-remembered-username";
|
||||
private const string RememberedCheckboxKey = "admin-remember-checkbox";
|
||||
|
||||
@@ -49,39 +59,83 @@
|
||||
{
|
||||
try
|
||||
{
|
||||
rememberedUsername = await LocalStorageService.GetItemAsStringAsync(RememberedUsernameKey) ?? "";
|
||||
username = await LocalStorageService.GetItemAsStringAsync(RememberedUsernameKey) ?? "";
|
||||
var checkboxValue = await LocalStorageService.GetItemAsStringAsync(RememberedCheckboxKey) ?? "false";
|
||||
isRememberChecked = checkboxValue == "true" && !string.IsNullOrEmpty(rememberedUsername);
|
||||
rememberMe = checkboxValue == "true" && !string.IsNullOrEmpty(username);
|
||||
}
|
||||
catch
|
||||
{
|
||||
rememberedUsername = "";
|
||||
isRememberChecked = false;
|
||||
username = "";
|
||||
rememberMe = false;
|
||||
}
|
||||
}
|
||||
|
||||
protected override async Task OnAfterRenderAsync(bool firstRender)
|
||||
private async Task HandleLogin()
|
||||
{
|
||||
if (firstRender)
|
||||
if (form == null || isLoggingIn) return;
|
||||
|
||||
await form.Validate();
|
||||
if (!form.IsValid) return;
|
||||
|
||||
isLoggingIn = true;
|
||||
try
|
||||
{
|
||||
try
|
||||
var response = await Http.PostAsJsonAsync("/api/auth/login", new { username, password });
|
||||
if (!response.IsSuccessStatusCode)
|
||||
{
|
||||
await Js.InvokeVoidAsync("taxbaikAdminSession.syncRouteClass");
|
||||
await Js.InvokeVoidAsync("taxbaikAdminSession.bindLoginForm");
|
||||
Snackbar.Add("로그인 실패: 사용자명 또는 비밀번호가 올바르지 않습니다", Severity.Error);
|
||||
return;
|
||||
}
|
||||
catch
|
||||
|
||||
var json = await response.Content.ReadAsStringAsync();
|
||||
var loginResponse = JsonSerializer.Deserialize<LoginResponse>(json);
|
||||
if (loginResponse == null || string.IsNullOrEmpty(loginResponse.AccessToken))
|
||||
{
|
||||
// Login UI must remain visible even if JS binding fails.
|
||||
Snackbar.Add("로그인 실패: 응답 오류", Severity.Error);
|
||||
return;
|
||||
}
|
||||
finally
|
||||
|
||||
// 로컬 저장소 저장
|
||||
await LocalStorageService.SetItemAsStringAsync("accessToken", loginResponse.AccessToken);
|
||||
await LocalStorageService.SetItemAsStringAsync("refreshToken", loginResponse.RefreshToken ?? "");
|
||||
var expiryTicks = DateTimeOffset.UtcNow.AddSeconds(loginResponse.ExpiresIn).UtcTicks;
|
||||
await LocalStorageService.SetItemAsStringAsync("tokenExpiry", expiryTicks.ToString());
|
||||
|
||||
// 아이디 저장
|
||||
if (rememberMe)
|
||||
{
|
||||
// Blazor owns this render from here on, so drive "disabled" from
|
||||
// C# state rather than a raw DOM mutation - otherwise this hydration
|
||||
// pass re-asserts the prerendered markup's static "disabled" and
|
||||
// silently undoes whatever the early inline <script> already set.
|
||||
isReady = true;
|
||||
StateHasChanged();
|
||||
await LocalStorageService.SetItemAsStringAsync(RememberedUsernameKey, username);
|
||||
await LocalStorageService.SetItemAsStringAsync(RememberedCheckboxKey, "true");
|
||||
}
|
||||
else
|
||||
{
|
||||
await LocalStorageService.RemoveItemAsync(RememberedUsernameKey);
|
||||
await LocalStorageService.RemoveItemAsync(RememberedCheckboxKey);
|
||||
}
|
||||
|
||||
// Blazor 인증 상태 업데이트
|
||||
if (AuthStateProvider is CustomAuthenticationStateProvider customProvider)
|
||||
{
|
||||
await customProvider.LoginAsync(loginResponse.AccessToken, loginResponse.RefreshToken ?? "", loginResponse.ExpiresIn);
|
||||
}
|
||||
|
||||
// 대시보드로 이동
|
||||
Navigation.NavigateTo("/admin/dashboard", replace: true);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
Snackbar.Add($"로그인 중 오류: {ex.Message}", Severity.Error);
|
||||
}
|
||||
finally
|
||||
{
|
||||
isLoggingIn = false;
|
||||
}
|
||||
}
|
||||
|
||||
private class LoginResponse
|
||||
{
|
||||
public string AccessToken { get; set; } = "";
|
||||
public string RefreshToken { get; set; } = "";
|
||||
public int ExpiresIn { get; set; }
|
||||
}
|
||||
}
|
||||
|
||||
@@ -127,6 +127,8 @@ public class CustomAuthenticationStateProvider : AuthenticationStateProvider
|
||||
await _localStorage.SetItemAsStringAsync("refreshToken", refreshToken);
|
||||
await _localStorage.SetItemAsStringAsync("tokenExpiry", tokenExpiryTicks.ToString());
|
||||
|
||||
// Blazor에 인증 상태 변경을 알림 - 이 호출 자체는 async이지만 fire-and-forget OK
|
||||
// (NotifyAuthenticationStateChanged는 내부적으로 Task를 구독함)
|
||||
NotifyAuthenticationStateChanged(GetAuthenticationStateAsync());
|
||||
}
|
||||
|
||||
|
||||
@@ -341,6 +341,9 @@ window.taxbaikAdminSession = {
|
||||
localStorage.removeItem('admin-remember-checkbox');
|
||||
}
|
||||
|
||||
// 토큰을 저장한 직후 페이지 리로드
|
||||
// 이렇게 하면 CustomAuthenticationStateProvider의 GetAuthenticationStateAsync()가
|
||||
// localStorage에서 토큰을 복원하고 [Authorize] 페이지가 제대로 렌더링됨
|
||||
window.location.href = '/taxbaik/admin/dashboard';
|
||||
} catch (error) {
|
||||
window.taxbaikAdminSession.traceUiState('admin-login', `submit failed: ${error?.message || 'login failed'}`);
|
||||
|
||||
Reference in New Issue
Block a user