feat: JWT 토큰 기반 Admin 로그인 인증 완성

- AuthService로 JWT 토큰 생성 및 검증
- CustomAuthenticationStateProvider를 통한 Blazor 인증 통합
- LocalStorageService로 토큰 관리
- Login.razor 완전 재작성 (실제 DB 검증, 토큰 발급)
- BCrypt 기반 비밀번호 검증
- admin/admin123으로 테스트 가능

Co-Authored-By: Claude Haiku 4.5 <noreply@anthropic.com>
This commit is contained in:
2026-06-26 22:00:16 +09:00
parent b2c8b35cdd
commit a039bb53a4
10 changed files with 274 additions and 34 deletions
+96
View File
@@ -0,0 +1,96 @@
using System.IdentityModel.Tokens.Jwt;
using System.Security.Claims;
using System.Text;
using BCrypt.Net;
using Microsoft.IdentityModel.Tokens;
using TaxBaik.Domain.Entities;
using TaxBaik.Domain.Interfaces;
namespace TaxBaik.Admin.Services;
public class AuthService
{
private readonly IAdminUserRepository _adminUserRepository;
private readonly ILogger<AuthService> _logger;
private readonly string _jwtSecretKey;
private readonly int _tokenExpirationMinutes = 480; // 8시간
public AuthService(IAdminUserRepository adminUserRepository, ILogger<AuthService> logger, IConfiguration configuration)
{
_adminUserRepository = adminUserRepository;
_logger = logger;
_jwtSecretKey = configuration["Jwt:SecretKey"] ?? throw new InvalidOperationException("Missing 'Jwt:SecretKey' configuration.");
}
public async Task<string?> AuthenticateAndGenerateTokenAsync(string username, string password)
{
if (string.IsNullOrWhiteSpace(username) || string.IsNullOrWhiteSpace(password))
{
return null;
}
var user = await _adminUserRepository.GetByUsernameAsync(username);
if (user == null)
{
_logger.LogWarning("로그인 시도: 존재하지 않는 사용자 '{Username}'", username);
return null;
}
if (!BCrypt.Net.BCrypt.Verify(password, user.PasswordHash))
{
_logger.LogWarning("로그인 시도: 잘못된 비밀번호 '{Username}'", username);
return null;
}
_logger.LogInformation("로그인 성공: {Username}", username);
return GenerateJwtToken(user);
}
private string GenerateJwtToken(AdminUser user)
{
var key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(_jwtSecretKey));
var creds = new SigningCredentials(key, SecurityAlgorithms.HmacSha256);
var claims = new[]
{
new Claim(ClaimTypes.NameIdentifier, user.Id.ToString()),
new Claim(ClaimTypes.Name, user.Username),
new Claim("username", user.Username)
};
var token = new JwtSecurityToken(
issuer: "taxbaik-admin",
audience: "taxbaik-admin-client",
claims: claims,
expires: DateTime.UtcNow.AddMinutes(_tokenExpirationMinutes),
signingCredentials: creds);
return new JwtSecurityTokenHandler().WriteToken(token);
}
public ClaimsPrincipal? ValidateToken(string token)
{
try
{
var key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(_jwtSecretKey));
var handler = new JwtSecurityTokenHandler();
var principal = handler.ValidateToken(token, new TokenValidationParameters
{
ValidateIssuerSigningKey = true,
IssuerSigningKey = key,
ValidateIssuer = true,
ValidIssuer = "taxbaik-admin",
ValidateAudience = true,
ValidAudience = "taxbaik-admin-client",
ValidateLifetime = true,
ClockSkew = TimeSpan.Zero
}, out SecurityToken validatedToken);
return principal;
}
catch
{
return null;
}
}
}
@@ -0,0 +1,59 @@
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()));
}
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);
var principal = _authService.ValidateToken(token);
NotifyAuthenticationStateChanged(GetAuthenticationStateAsync());
}
public async Task LogoutAsync()
{
await _localStorage.RemoveItemAsync("auth_token");
NotifyAuthenticationStateChanged(GetAuthenticationStateAsync());
}
}
@@ -0,0 +1,8 @@
namespace TaxBaik.Admin.Services;
public interface ILocalStorageService
{
Task<string?> GetItemAsStringAsync(string key);
Task SetItemAsStringAsync(string key, string value);
Task RemoveItemAsync(string key);
}
@@ -0,0 +1,43 @@
using Microsoft.JSInterop;
namespace TaxBaik.Admin.Services;
public class LocalStorageService : ILocalStorageService
{
private readonly IJSRuntime _jsRuntime;
public LocalStorageService(IJSRuntime jsRuntime)
{
_jsRuntime = jsRuntime;
}
public async Task<string?> GetItemAsStringAsync(string key)
{
try
{
return await _jsRuntime.InvokeAsync<string>("localStorage.getItem", key);
}
catch
{
return null;
}
}
public async Task SetItemAsStringAsync(string key, string value)
{
try
{
await _jsRuntime.InvokeVoidAsync("localStorage.setItem", key, value);
}
catch { }
}
public async Task RemoveItemAsync(string key)
{
try
{
await _jsRuntime.InvokeVoidAsync("localStorage.removeItem", key);
}
catch { }
}
}