SPMS_API/SPMS.API/Middlewares/ServiceCodeMiddleware.cs
SEAN df8a8e2e5b feat: X-Service-Code / X-API-KEY 서비스 식별 미들웨어 구현 (#32)
- ServiceRepository: IServiceRepository 구현 (GetByServiceCode, GetByApiKey)
- ServiceCodeMiddleware: X-Service-Code 헤더 검증, DB 조회, 서비스 상태 확인
- ApiKeyMiddleware: /v1/in/device/* 경로 X-API-KEY 검증
- ApplicationBuilderExtensions: 미들웨어 파이프라인 12~13번 등록
- DependencyInjection: IServiceRepository DI 등록

Closes #32
2026-02-09 17:25:19 +09:00

57 lines
1.9 KiB
C#

using SPMS.Domain.Common;
using SPMS.Domain.Enums;
using SPMS.Domain.Interfaces;
namespace SPMS.API.Middlewares;
public class ServiceCodeMiddleware
{
private readonly RequestDelegate _next;
public ServiceCodeMiddleware(RequestDelegate next) => _next = next;
public async Task InvokeAsync(HttpContext context, IServiceRepository serviceRepository)
{
if (context.Request.Path.StartsWithSegments("/v1/out") ||
context.Request.Path.StartsWithSegments("/swagger") ||
context.Request.Path.StartsWithSegments("/health"))
{
await _next(context);
return;
}
if (!context.Request.Headers.TryGetValue("X-Service-Code", out var serviceCode) ||
string.IsNullOrWhiteSpace(serviceCode))
{
context.Response.StatusCode = 400;
context.Response.ContentType = "application/json";
await context.Response.WriteAsJsonAsync(
ApiResponse.Fail(ErrorCodes.BadRequest, "X-Service-Code 헤더가 필요합니다."));
return;
}
var service = await serviceRepository.GetByServiceCodeAsync(serviceCode!);
if (service == null)
{
context.Response.StatusCode = 404;
context.Response.ContentType = "application/json";
await context.Response.WriteAsJsonAsync(
ApiResponse.Fail(ErrorCodes.NotFound, "존재하지 않는 서비스입니다."));
return;
}
if (service.Status != ServiceStatus.Active)
{
context.Response.StatusCode = 503;
context.Response.ContentType = "application/json";
await context.Response.WriteAsJsonAsync(
ApiResponse.Fail(ErrorCodes.Unauthorized, "비활성 상태의 서비스입니다."));
return;
}
context.Items["Service"] = service;
context.Items["ServiceId"] = service.Id;
await _next(context);
}
}