using Back.Program.Common.Auth.Interface; using Back.Program.Common.Data; using Microsoft.EntityFrameworkCore; namespace Back.Program.Common.Auth { /// public class APIHeaderMiddleware { private readonly RequestDelegate _next; private readonly string[] _headerNames; // private readonly IHeaderConfig _headerConfig; public APIHeaderMiddleware(RequestDelegate next, string[] headerNames) //, IHeaderConfig headerConfig) { _next = next; _headerNames = headerNames; } public async Task Invoke(HttpContext context) { if (context.Request.Path.Equals("/api/v1/in/app", StringComparison.OrdinalIgnoreCase)) { await _next(context); return; } if (context.Request.Path.Value != null && context.Request.Path.Value.Contains("/out/")) { await _next(context); return; } // 정적 파일 요청은 미들웨어 건너뜀 var path = context.Request.Path.Value; if (path != null && (path.StartsWith("/api"))) { // Scoped 사용해서 값 가져오는 곳임 var headerConfig = context.RequestServices.GetRequiredService(); bool valid = false; foreach (var header in _headerNames) { // context.Request.Headers.TryGetValue(header, out var headerValue) // header 를 찾는데 header if (context.Request.Headers.TryGetValue(header, out var headerValue) && !string.IsNullOrWhiteSpace(headerValue)) { var keyName = await headerConfig.GetExpectedHeaderValueAsync(headerValue); if (keyName != string.Empty) { valid = true; break; } } } if (!valid) { context.Response.StatusCode = StatusCodes.Status401Unauthorized; await context.Response.WriteAsync($"Invalid header value"); return; } await _next(context); return; } await _next(context); } } }