refactor: Web과 Admin 통합 - 단일 포트 5001로 운영
TaxBaik CI/CD / build-and-deploy (push) Failing after 36s

분리의 단점을 제거하고 단일 앱으로 통합:

구조 변경:
- TaxBaik.Admin → TaxBaik.Web/Components/Admin/
- Admin Services → TaxBaik.Web/Services/
- 포트: 5001 (기존 5002 제거)

경로:
- 홈페이지: http://localhost:5001/taxbaik
- 관리자: http://localhost:5001/taxbaik/admin

기술:
- Razor Pages (Web) + Blazor Server (Admin) 통합
- 단일 Program.cs로 양쪽 모두 지원
- JWT 인증 유지
- MudBlazor UI 유지

장점:
- 개발 복잡도 감소 (터미널 1개)
- 배포 단순화 (앱 1개)
- DB 마이그레이션 1회 실행

Co-Authored-By: Claude Haiku 4.5 <noreply@anthropic.com>
This commit is contained in:
2026-06-26 22:35:21 +09:00
parent 17cbf4e40b
commit 57269e281d
53 changed files with 46 additions and 1665 deletions
+19
View File
@@ -0,0 +1,19 @@
<!DOCTYPE html>
<html lang="ko">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>백원숙 세무회계 - 관리자</title>
<base href="/taxbaik/admin/" />
<link href="https://fonts.googleapis.com/css2?family=Noto+Sans+KR:wght@400;500;700&display=swap" rel="stylesheet" />
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet" />
<link href="https://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet" />
<link rel="stylesheet" href="~/css/admin.css" />
<component type="typeof(HeadOutlet)" render-mode="InteractiveServer" />
</head>
<body>
<Routes />
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
<script src="_framework/blazor.web.js"></script>
</body>
</html>
@@ -0,0 +1,18 @@
@using MudBlazor
<MudDialog>
<DialogContent>
<MudText>정말로 삭제하시겠습니까?</MudText>
</DialogContent>
<DialogActions>
<MudButton OnClick="@Cancel">취소</MudButton>
<MudButton Color="Color.Error" OnClick="@Confirm">삭제</MudButton>
</DialogActions>
</MudDialog>
@code {
[CascadingParameter] MudDialogInstance MudDialog { get; set; }
void Cancel() => MudDialog.Cancel();
void Confirm() => MudDialog.Close(DialogResult.Ok(true));
}
@@ -0,0 +1,58 @@
@using TaxBaik.Domain.Interfaces
@inject IInquiryRepository InquiryRepository
<MudSimpleTable Striped="true" Dense="true" Class="mt-4">
<thead>
<tr>
<th>이름</th>
<th>전화</th>
<th>분야</th>
<th>메시지</th>
<th>날짜</th>
<th></th>
</tr>
</thead>
<tbody>
@foreach (var inquiry in filteredInquiries)
{
<tr>
<td>@inquiry.Name</td>
<td>@inquiry.Phone</td>
<td>@inquiry.ServiceType</td>
<td>@inquiry.Message.Substring(0, Math.Min(30, inquiry.Message.Length))...</td>
<td>@inquiry.CreatedAt.ToString("yyyy-MM-dd")</td>
<td>
<MudButton Size="Size.Small" Variant="Variant.Text"
Href="@($"/taxbaik/admin/inquiries/{inquiry.Id}")">보기</MudButton>
</td>
</tr>
}
</tbody>
</MudSimpleTable>
@code {
[Parameter]
public string Status { get; set; } = "";
private List<Domain.Entities.Inquiry> inquiries = [];
private List<Domain.Entities.Inquiry> filteredInquiries = [];
protected override async Task OnInitializedAsync()
{
var (items, _) = await InquiryRepository.GetPagedAsync(1, 1000);
inquiries = items.ToList();
FilterInquiries();
}
private void FilterInquiries()
{
filteredInquiries = string.IsNullOrEmpty(Status)
? inquiries
: inquiries.Where(x => x.Status == Status).ToList();
}
protected override async Task OnParametersSetAsync()
{
FilterInquiries();
}
}
@@ -0,0 +1,7 @@
@inherits LayoutComponentBase
<MudThemeProvider />
<MudDialogProvider />
<MudSnackbarProvider />
@Body
@@ -0,0 +1,41 @@
@using Microsoft.AspNetCore.Components.Authorization
@inherits LayoutComponentBase
<AuthorizeView>
<Authorized>
<MudThemeProvider />
<MudDialogProvider />
<MudSnackbarProvider />
<MudLayout>
<MudAppBar Elevation="1">
<MudText Typo="Typo.h6" Class="ml-3">백원숙 세무회계 관리자</MudText>
<MudSpacer />
<MudButton Color="Color.Inherit" Href="/taxbaik">공개 사이트</MudButton>
<MudButton Href="/taxbaik/admin/logout">로그아웃</MudButton>
</MudAppBar>
<MudDrawer @bind-open="@drawerOpen" Elevation="1">
<MudNavMenu>
<MudNavLink Href="/taxbaik/admin/" Match="NavLinkMatch.All">📊 대시보드</MudNavLink>
<MudNavLink Href="/taxbaik/admin/blog">📝 블로그 관리</MudNavLink>
<MudNavLink Href="/taxbaik/admin/inquiries">💬 문의 관리</MudNavLink>
<MudNavLink Href="/taxbaik/admin/settings">⚙️ 설정</MudNavLink>
</MudNavMenu>
</MudDrawer>
<MudMainContent>
<MudContainer MaxWidth="MaxWidth.Large" Class="my-4">
@Body
</MudContainer>
</MudMainContent>
</MudLayout>
</Authorized>
<NotAuthorized>
@Body
</NotAuthorized>
</AuthorizeView>
@code {
private bool drawerOpen = true;
}
@@ -0,0 +1,77 @@
@page "/admin/blog/create"
@using TaxBaik.Application.Services
@using TaxBaik.Domain.Interfaces
@attribute [Authorize]
@inject BlogService BlogService
@inject ICategoryRepository CategoryRepository
@inject NavigationManager Navigation
@inject Snackbar Snackbar
<PageTitle>새 포스트 작성</PageTitle>
<MudText Typo="Typo.h5" Class="mb-4">📝 새 포스트</MudText>
<MudPaper Class="pa-4" Elevation="1">
<MudForm @ref="form">
<MudTextField @bind-Value="model.Title" Label="제목"
Variant="Variant.Outlined" Class="mb-4" Required="true" />
<MudSelect @bind-Value="model.CategoryId" Label="카테고리"
Variant="Variant.Outlined" Class="mb-4">
@foreach (var category in categories)
{
<MudSelectItem Value="@category.Id">@category.Name</MudSelectItem>
}
</MudSelect>
<MudTextField @bind-Value="model.Content" Label="본문"
Variant="Variant.Outlined" Lines="10" Class="mb-4" Required="true" />
<MudTextField @bind-Value="model.Tags" Label="태그 (쉼표로 구분)"
Variant="Variant.Outlined" Class="mb-4" />
<MudTextField @bind-Value="model.SeoTitle" Label="SEO 제목"
Variant="Variant.Outlined" Class="mb-4" />
<MudTextField @bind-Value="model.SeoDescription" Label="SEO 설명"
Variant="Variant.Outlined" Lines="3" Class="mb-4" />
<MudCheckBox @bind-Checked="model.IsPublished" Label="즉시 발행" Class="mb-4" />
<div class="d-flex gap-2">
<MudButton Variant="Variant.Filled" Color="Color.Primary"
@onclick="SavePost">저장</MudButton>
<MudButton Variant="Variant.Outlined" @onclick="@(() => Navigation.NavigateTo("/taxbaik/admin/blog"))">
취소
</MudButton>
</div>
</MudForm>
</MudPaper>
@code {
private MudForm form;
private List<Domain.Entities.Category> categories = [];
private CreatePostModel model = new();
protected override async Task OnInitializedAsync()
{
categories = (await CategoryRepository.GetAllAsync()).ToList();
}
private async Task SavePost()
{
// TODO: Implement BlogService.CreateAsync
Navigation.NavigateTo("/taxbaik/admin/blog");
}
private class CreatePostModel
{
public string Title { get; set; }
public string Content { get; set; }
public int CategoryId { get; set; }
public string Tags { get; set; }
public string SeoTitle { get; set; }
public string SeoDescription { get; set; }
public bool IsPublished { get; set; }
}
}
@@ -0,0 +1,69 @@
@page "/admin/blog"
@using TaxBaik.Application.Services
@using TaxBaik.Domain.Interfaces
@attribute [Authorize]
@inject IBlogPostRepository BlogRepository
@inject DialogService DialogService
@inject Snackbar Snackbar
<PageTitle>블로그 관리</PageTitle>
<div class="mb-4 d-flex justify-content-between align-items-center">
<MudText Typo="Typo.h5">📝 블로그 관리</MudText>
<MudButton Variant="Variant.Filled" Color="Color.Primary"
Href="/taxbaik/admin/blog/create">새 포스트</MudButton>
</div>
<MudDataGrid Items="@posts" Striped="true" Hoverable="true" Loading="@isLoading">
<Columns>
<PropertyColumn Property="x => x.Title" Title="제목" />
<PropertyColumn Property="x => x.IsPublished" Title="발행">
<CellTemplate Context="cell">
<MudCheckBox @bind-Checked="@cell.Item.IsPublished" />
</CellTemplate>
</PropertyColumn>
<PropertyColumn Property="x => x.ViewCount" Title="조회수" />
<PropertyColumn Property="x => x.CreatedAt" Title="작성일" Format="yyyy-MM-dd" />
<TemplateColumn>
<CellTemplate Context="cell">
<MudButton Variant="Variant.Text" Color="Color.Primary"
Href="@($"/taxbaik/admin/blog/{cell.Item.Id}/edit")">수정</MudButton>
<MudButton Variant="Variant.Text" Color="Color.Error"
@onclick="@(async () => await DeletePost(cell.Item.Id))">삭제</MudButton>
</CellTemplate>
</TemplateColumn>
</Columns>
</MudDataGrid>
@code {
private List<Domain.Entities.BlogPost> posts = [];
private bool isLoading = true;
protected override async Task OnInitializedAsync()
{
await LoadPosts();
}
private async Task LoadPosts()
{
isLoading = true;
try
{
var items = await BlogRepository.GetAllForAdminAsync();
posts = items.ToList();
}
catch { }
isLoading = false;
}
private async Task TogglePublish(int postId, bool isPublished)
{
// TODO: Update publish status via service
}
private async Task DeletePost(int postId)
{
// TODO: Delete via repository
await LoadPosts();
}
}
@@ -0,0 +1,92 @@
@page "/admin/dashboard"
@using TaxBaik.Application.Services
@using TaxBaik.Domain.Interfaces
@attribute [Authorize]
@inject IInquiryRepository InquiryRepository
@inject BlogService BlogService
<PageTitle>대시보드</PageTitle>
<MudText Typo="Typo.h5" Class="mb-4">📊 대시보드</MudText>
<MudGrid>
<MudItem xs="12" sm="6" md="3">
<MudPaper Class="pa-4" Elevation="1">
<MudText Typo="Typo.subtitle2">이번달 문의</MudText>
<MudText Typo="Typo.h4">@thisMonthInquiries</MudText>
</MudPaper>
</MudItem>
<MudItem xs="12" sm="6" md="3">
<MudPaper Class="pa-4" Elevation="1">
<MudText Typo="Typo.subtitle2">신규 문의</MudText>
<MudText Typo="Typo.h4">@newInquiries</MudText>
</MudPaper>
</MudItem>
<MudItem xs="12" sm="6" md="3">
<MudPaper Class="pa-4" Elevation="1">
<MudText Typo="Typo.subtitle2">전체 포스트</MudText>
<MudText Typo="Typo.h4">@totalPosts</MudText>
</MudPaper>
</MudItem>
<MudItem xs="12" sm="6" md="3">
<MudPaper Class="pa-4" Elevation="1">
<MudText Typo="Typo.subtitle2">발행된 포스트</MudText>
<MudText Typo="Typo.h4">@publishedPosts</MudText>
</MudPaper>
</MudItem>
</MudGrid>
<MudPaper Class="pa-4 mt-4" Elevation="1">
<MudText Typo="Typo.h6" Class="mb-3">최근 문의</MudText>
<MudSimpleTable Striped="true" Dense="true">
<thead>
<tr>
<th>이름</th>
<th>전화</th>
<th>분야</th>
<th>상태</th>
<th>날짜</th>
</tr>
</thead>
<tbody>
@foreach (var inquiry in recentInquiries)
{
<tr>
<td>@inquiry.Name</td>
<td>@inquiry.Phone</td>
<td>@inquiry.ServiceType</td>
<td>
<MudChip Size="Size.Small"
Color="@(inquiry.Status == "new" ? Color.Warning : inquiry.Status == "contacted" ? Color.Info : Color.Success)">
@inquiry.Status
</MudChip>
</td>
<td>@inquiry.CreatedAt.ToString("yyyy-MM-dd")</td>
</tr>
}
</tbody>
</MudSimpleTable>
</MudPaper>
@code {
private int thisMonthInquiries = 0;
private int newInquiries = 0;
private int totalPosts = 0;
private int publishedPosts = 0;
private List<Domain.Entities.Inquiry> recentInquiries = [];
protected override async Task OnInitializedAsync()
{
var (inquiries, total) = await InquiryRepository.GetPagedAsync(1, 100);
recentInquiries = inquiries.OrderByDescending(x => x.CreatedAt).Take(5).ToList();
var now = DateTime.UtcNow;
thisMonthInquiries = inquiries.Count(x => x.CreatedAt.Year == now.Year && x.CreatedAt.Month == now.Month);
newInquiries = inquiries.Count(x => x.Status == "new");
totalPosts = 0; // TODO: get from blog service
publishedPosts = 0; // TODO: get from blog service
}
}
@@ -0,0 +1,64 @@
@page "/admin/inquiries/{InquiryId:int}"
@using TaxBaik.Domain.Interfaces
@attribute [Authorize]
@inject IInquiryRepository InquiryRepository
@inject NavigationManager Navigation
<PageTitle>문의 상세</PageTitle>
@if (inquiry != null)
{
<MudButton Variant="Variant.Text" @onclick="@(() => Navigation.NavigateTo("/taxbaik/admin/inquiries"))">
← 돌아가기
</MudButton>
<MudPaper Class="pa-4 mt-4" Elevation="1">
<MudGrid>
<MudItem xs="12" md="6">
<MudText Typo="Typo.subtitle1">이름</MudText>
<MudText>@inquiry.Name</MudText>
</MudItem>
<MudItem xs="12" md="6">
<MudText Typo="Typo.subtitle1">연락처</MudText>
<MudText>@inquiry.Phone</MudText>
</MudItem>
<MudItem xs="12" md="6">
<MudText Typo="Typo.subtitle1">이메일</MudText>
<MudText>@inquiry.Email</MudText>
</MudItem>
<MudItem xs="12" md="6">
<MudText Typo="Typo.subtitle1">분야</MudText>
<MudText>@inquiry.ServiceType</MudText>
</MudItem>
<MudItem xs="12">
<MudText Typo="Typo.subtitle1">메시지</MudText>
<MudText>@inquiry.Message</MudText>
</MudItem>
<MudItem xs="12">
<MudText Typo="Typo.subtitle1">상태</MudText>
<MudSelect @bind-Value="inquiry.Status" Label="상태 변경">
<MudSelectItem Value="@("new")">신규</MudSelectItem>
<MudSelectItem Value="@("contacted")">연락함</MudSelectItem>
<MudSelectItem Value="@("completed")">완료</MudSelectItem>
</MudSelect>
</MudItem>
</MudGrid>
</MudPaper>
}
else
{
<MudText>문의를 찾을 수 없습니다.</MudText>
}
@code {
[Parameter]
public int InquiryId { get; set; }
private Domain.Entities.Inquiry inquiry;
protected override async Task OnInitializedAsync()
{
var (inquiries, _) = await InquiryRepository.GetPagedAsync(1, 1000);
inquiry = inquiries.FirstOrDefault(x => x.Id == InquiryId);
}
}
@@ -0,0 +1,23 @@
@page "/admin/inquiries"
@using TaxBaik.Domain.Interfaces
@attribute [Authorize]
@inject IInquiryRepository InquiryRepository
<PageTitle>문의 관리</PageTitle>
<MudText Typo="Typo.h5" Class="mb-4">💬 문의 관리</MudText>
<MudTabs>
<MudTabPanel Text="전체">
<InquiryTable Status="" />
</MudTabPanel>
<MudTabPanel Text="신규">
<InquiryTable Status="new" />
</MudTabPanel>
<MudTabPanel Text="연락함">
<InquiryTable Status="contacted" />
</MudTabPanel>
<MudTabPanel Text="완료">
<InquiryTable Status="completed" />
</MudTabPanel>
</MudTabs>
@@ -0,0 +1,85 @@
@page "/admin/login"
@using System.ComponentModel.DataAnnotations
@layout TaxBaik.Web.Components.Admin.Layout.BlankLayout
@attribute [AllowAnonymous]
@inject AuthService AuthService
@inject NavigationManager NavigationManager
@inject CustomAuthenticationStateProvider AuthStateProvider
<PageTitle>로그인</PageTitle>
<MudContainer MaxWidth="MaxWidth.Small" Class="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>
<MudForm @ref="form" @bind-IsValid="@isFormValid">
<MudTextField @bind-Value="model.Username" Label="사용자명"
Variant="Variant.Outlined" Required="true" Class="mb-4" />
<MudTextField @bind-Value="model.Password" Label="비밀번호" InputType="InputType.Password"
Variant="Variant.Outlined" Required="true" Class="mb-4" />
@if (!string.IsNullOrEmpty(errorMessage))
{
<MudAlert Severity="Severity.Error" Class="mb-4">@errorMessage</MudAlert>
}
<MudButton Variant="Variant.Filled" Color="Color.Primary" FullWidth="true"
Size="Size.Large" OnClick="HandleLogin" Disabled="isLoading">
@if (isLoading)
{
<MudProgressCircular Size="Size.Small" Indeterminate="true" Class="mr-2" />
<span>로그인 중...</span>
}
else
{
<span>로그인</span>
}
</MudButton>
</MudForm>
</MudPaper>
</MudContainer>
@code {
private MudForm form;
private bool isFormValid = false;
private bool isLoading = false;
private string errorMessage = "";
private LoginModel model = new();
private async Task HandleLogin()
{
if (isLoading)
return;
isLoading = true;
errorMessage = "";
try
{
var token = await AuthService.AuthenticateAndGenerateTokenAsync(model.Username, model.Password);
if (token == null)
{
errorMessage = "사용자명 또는 비밀번호가 올바르지 않습니다.";
isLoading = false;
return;
}
await AuthStateProvider.LoginAsync(token);
NavigationManager.NavigateTo("/taxbaik/admin/dashboard", forceLoad: false);
}
catch (Exception ex)
{
errorMessage = "로그인 중 오류가 발생했습니다.";
isLoading = false;
}
}
private class LoginModel
{
public string Username { get; set; } = "";
public string Password { get; set; } = "";
}
}
@@ -0,0 +1,39 @@
@page "/admin/settings"
@using TaxBaik.Domain.Interfaces
@attribute [Authorize]
@inject Snackbar Snackbar
<PageTitle>설정</PageTitle>
<MudText Typo="Typo.h5" Class="mb-4">⚙️ 사이트 설정</MudText>
<MudPaper Class="pa-4" Elevation="1">
<MudForm>
<MudTextField @bind-Value="phone" Label="전화번호"
Variant="Variant.Outlined" Class="mb-4" />
<MudTextField @bind-Value="email" Label="이메일"
Variant="Variant.Outlined" Class="mb-4" />
<MudTextField @bind-Value="kakaoUrl" Label="카카오 채널 URL"
Variant="Variant.Outlined" Class="mb-4" />
<MudTextField @bind-Value="instagramUrl" Label="인스타그램"
Variant="Variant.Outlined" Class="mb-4" />
<MudButton Variant="Variant.Filled" Color="Color.Primary"
@onclick="SaveSettings">저장</MudButton>
</MudForm>
</MudPaper>
@code {
private string phone = "010-4122-8268";
private string email = "taxbaik5668@gmail.com";
private string kakaoUrl = "http://pf.kakao.com/_xoxchTX";
private string instagramUrl = "https://www.instagram.com/taxtory5668/";
private async Task SaveSettings()
{
// TODO: Save settings to database
}
}
+17
View File
@@ -0,0 +1,17 @@
@using Microsoft.AspNetCore.Components.Routing
@using Microsoft.AspNetCore.Components.Authorization
<CascadingAuthenticationState>
<Router AppAssembly="typeof(Program).Assembly">
<Found Context="routeData">
<AuthorizeRouteView RouteData="routeData" DefaultLayout="typeof(TaxBaik.Web.Components.Admin.Layout.MainLayout)" />
<FocusOnNavigate RouteData="routeData" Selector="h1" />
</Found>
<NotFound>
<PageTitle>찾을 수 없음</PageTitle>
<LayoutView Layout="typeof(TaxBaik.Web.Components.Admin.Layout.MainLayout)">
<p>요청한 페이지를 찾을 수 없습니다.</p>
</LayoutView>
</NotFound>
</Router>
</CascadingAuthenticationState>
@@ -0,0 +1,13 @@
@using System.Net.Http
@using System.Net.Http.Json
@using Microsoft.AspNetCore.Components.Forms
@using Microsoft.AspNetCore.Components.Routing
@using Microsoft.AspNetCore.Components.Web
@using Microsoft.AspNetCore.Components.Web.Virtualization
@using Microsoft.AspNetCore.Components.Authorization
@using Microsoft.AspNetCore.Authorization
@using MudBlazor
@using TaxBaik.Web.Services
@using TaxBaik.Domain.Entities
@using TaxBaik.Application.Services
@attribute [Authorize]
+19
View File
@@ -1,13 +1,29 @@
using System.IO.Compression;
using System.Text.Encodings.Web;
using System.Text.Unicode;
using Microsoft.AspNetCore.Components.Authorization;
using Microsoft.AspNetCore.ResponseCompression;
using MudBlazor.Services;
using TaxBaik.Application;
using TaxBaik.Infrastructure;
using TaxBaik.Web.Services;
var builder = WebApplication.CreateBuilder(args);
// Razor Pages + Blazor Server 통합
builder.Services.AddRazorPages();
builder.Services.AddRazorComponents().AddInteractiveServerComponents();
// Blazor 인증
builder.Services.AddScoped<AuthService>();
builder.Services.AddScoped<CustomAuthenticationStateProvider>();
builder.Services.AddScoped<AuthenticationStateProvider>(sp => sp.GetRequiredService<CustomAuthenticationStateProvider>());
builder.Services.AddScoped<ILocalStorageService, LocalStorageService>();
builder.Services.AddCascadingAuthenticationState();
builder.Services.AddAuthorizationCore();
// UI & 캐시
builder.Services.AddMudServices();
builder.Services.AddMemoryCache();
builder.Services.AddResponseCompression(opts => {
opts.Providers.Add<GzipCompressionProvider>();
@@ -58,6 +74,7 @@ app.UsePathBase("/taxbaik");
app.UseResponseCompression();
app.UseStaticFiles();
app.UseRouting();
app.UseAuthorization();
app.UseAntiforgery();
if (!app.Environment.IsDevelopment())
@@ -66,6 +83,8 @@ if (!app.Environment.IsDevelopment())
app.UseHsts();
}
// Razor Pages + Blazor 매핑
app.MapRazorPages();
app.MapRazorComponents<TaxBaik.Web.Components.Admin.App>().AddInteractiveServerRenderMode();
app.Run();
+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.Web.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,79 @@
using System.IdentityModel.Tokens.Jwt;
using System.Security.Claims;
using Microsoft.AspNetCore.Components.Authorization;
namespace TaxBaik.Web.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;
}
}
}
@@ -0,0 +1,8 @@
namespace TaxBaik.Web.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.Web.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 { }
}
}
+7
View File
@@ -11,4 +11,11 @@
<ImplicitUsings>enable</ImplicitUsings>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="MudBlazor" Version="6.9.4" />
<PackageReference Include="BCrypt.Net-Next" Version="4.0.3" />
<PackageReference Include="System.IdentityModel.Tokens.Jwt" Version="8.2.1" />
<PackageReference Include="Microsoft.IdentityModel.Tokens" Version="8.2.1" />
</ItemGroup>
</Project>
+3
View File
@@ -8,6 +8,9 @@
"ConnectionStrings": {
"Default": "Host=localhost;Database=taxbaikdb;Username=taxbaik;Password=taxbaik123"
},
"Jwt": {
"SecretKey": "dev-secret-key-change-in-production-min-32-chars!"
},
"SiteSettings": {
"PhoneNumber": "010-4122-8268",
"EmailAddress": "taxbaik5668@gmail.com",