Files
taxbaik/TaxBaik.Web/Program.cs
T
kjh2064 1ad720afe6
TaxBaik CI/CD / build-and-deploy (push) Successful in 1m4s
TaxBaik Browser E2E / browser-e2e (push) Successful in 1m25s
fix: 배포 502 / 관리자 401 개선
- Program.cs: MapRazorComponents에 AllowAnonymous 추가
  JWT 미들웨어가 Blazor 셸 요청을 401로 차단하던 문제 수정
  (인증은 Blazor AuthorizeRouteView → RedirectToLogin에서 처리)
- deploy.yml: SSH 1회 연결로 배포+헬스체크 통합
  서버 사이드 폴링으로 대기(최대 120초), CI 측 sleep 제거
  구 배포 디렉토리 최근 5개 자동 정리
  secrets 파일 사전 검증 추가
- maintenance.html: 배포 중 Nginx가 직접 서빙할 점검 페이지
  15초 자동 새로고침, 카카오 채널 링크 포함

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-06-27 22:56:46 +09:00

152 lines
5.1 KiB
C#

using System.IO.Compression;
using System.Text;
using System.Text.Encodings.Web;
using System.Text.Unicode;
using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.AspNetCore.Components.Authorization;
using Microsoft.AspNetCore.HttpOverrides;
using Microsoft.AspNetCore.ResponseCompression;
using Microsoft.IdentityModel.Tokens;
using MudBlazor.Services;
using TaxBaik.Application;
using TaxBaik.Application.Services;
using TaxBaik.Infrastructure;
using TaxBaik.Web.Services;
var builder = WebApplication.CreateBuilder(args);
var isProduction = builder.Environment.IsProduction();
// Controllers (API)
builder.Services.AddControllers();
builder.Services.AddProblemDetails();
builder.Services.AddHealthChecks();
// Razor Pages + Blazor Server 통합
builder.Services.AddRazorPages();
builder.Services.AddRazorComponents().AddInteractiveServerComponents();
builder.Services.Configure<Microsoft.AspNetCore.Components.Server.CircuitOptions>(options =>
{
options.DetailedErrors = true;
});
// JWT 인증
var connectionString = builder.Configuration.GetConnectionString("Default")
?? throw new InvalidOperationException("Missing connection string");
var jwtKey = builder.Configuration["Jwt:SecretKey"] ?? throw new InvalidOperationException("Missing JWT SecretKey");
if (isProduction && jwtKey.Contains("dev-secret", StringComparison.OrdinalIgnoreCase))
throw new InvalidOperationException("Production JWT SecretKey must not use the development default.");
var key = Encoding.ASCII.GetBytes(jwtKey);
builder.Services.AddAuthentication(opts =>
{
opts.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
opts.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
})
.AddJwtBearer(opts =>
{
opts.TokenValidationParameters = new TokenValidationParameters
{
ValidateIssuerSigningKey = true,
IssuerSigningKey = new SymmetricSecurityKey(key),
ValidateIssuer = true,
ValidIssuer = "taxbaik-admin",
ValidateAudience = true,
ValidAudience = "taxbaik-admin-client",
ValidateLifetime = true,
ClockSkew = TimeSpan.FromMinutes(1)
};
});
// 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.AddAuthorization();
builder.Services.AddAuthorizationCore();
// HTTP Client for API
builder.Services.AddHttpClient<IApiClient, ApiClient>();
// UI & 캐시
builder.Services.AddMudServices();
builder.Services.AddMemoryCache();
builder.Services.AddResponseCompression(opts => {
opts.Providers.Add<GzipCompressionProvider>();
});
builder.Services.AddScoped<IInquiryNotificationService, TelegramInquiryNotificationService>();
// 한글 포함 다국어 문자를 유니코드 엔티티로 변환하지 않도록 설정
builder.Services.AddSingleton(HtmlEncoder.Create(UnicodeRanges.All));
builder.Services.AddInfrastructure();
builder.Services.AddApplication();
// Register version info
var versionInfo = new VersionInfo();
var versionFilePath = Path.Combine(AppContext.BaseDirectory, "wwwroot", "version.txt");
if (File.Exists(versionFilePath))
{
var lines = File.ReadAllLines(versionFilePath);
foreach (var line in lines)
{
if (line.StartsWith("Version:"))
versionInfo.Version = line.Substring("Version:".Length).Trim();
else if (line.StartsWith("Built:"))
versionInfo.Built = line.Substring("Built:".Length).Trim();
}
}
builder.Services.AddSingleton(versionInfo);
var app = builder.Build();
app.UseForwardedHeaders(new ForwardedHeadersOptions
{
ForwardedHeaders = ForwardedHeaders.XForwardedFor | ForwardedHeaders.XForwardedProto
});
// Run migrations on startup (non-blocking for development)
try
{
using (var scope = app.Services.CreateScope())
{
var connectionFactory = scope.ServiceProvider.GetRequiredService<TaxBaik.Domain.Interfaces.IDbConnectionFactory>();
var migrationRunner = new TaxBaik.Infrastructure.Data.MigrationRunner(connectionString, connectionFactory);
await migrationRunner.RunAsync();
}
}
catch (Exception ex)
{
if (!app.Environment.IsDevelopment())
throw;
Console.WriteLine($"Migration warning (development only): {ex.Message}");
}
app.UsePathBase("/taxbaik");
app.UseResponseCompression();
app.UseStaticFiles();
app.UseRouting();
app.UseAuthentication();
app.UseAuthorization();
app.UseAntiforgery();
if (!app.Environment.IsDevelopment())
{
app.UseExceptionHandler("/Error");
app.UseHsts();
}
// API + Razor Pages + Blazor 매핑
app.MapControllers();
app.MapHealthChecks("/healthz");
app.MapRazorPages();
// AllowAnonymous: JWT 미들웨어가 Blazor 셸 요청을 401로 차단하지 않도록 한다.
// 인증은 Blazor AuthorizeRouteView → RedirectToLogin 에서 처리한다.
app.MapRazorComponents<TaxBaik.Web.Components.Admin.App>()
.AddInteractiveServerRenderMode()
.AllowAnonymous();
app.Run();