[] API Header 점검하는 로직 추가 중2

This commit is contained in:
김선규 2025-03-18 18:00:22 +09:00
parent 1f8ac2cff7
commit 643708627a
2 changed files with 33 additions and 13 deletions

View File

@ -179,7 +179,8 @@ else
// app.UseHttpsRedirection();
// 헤더 미들웨어 부분
app.UseMiddleware<APIHeaderMiddle>("HEAD-CHECK");
app.UseMiddleware<APIHeaderMiddleware>(new string[] { "X-MyHeader1", "X-MyHeader2", "X-MyHeader3" });
// 이부분 봐야 합니다.
// app.UseMiddleware<CustomHeaderMiddleware>("X-MyHeader");

View File

@ -28,38 +28,57 @@ public class HeaderConfigRepository : IHeaderConfig
}
public class APIHeaderMiddle
public class APIHeaderMiddleware
{
private readonly RequestDelegate _next;
private readonly string _headerName;
private readonly string[] _headerNames;
private readonly IHeaderConfig _headerConfig;
public APIHeaderMiddle(RequestDelegate next, string headerName, IHeaderConfig headerConfig)
public APIHeaderMiddleware(RequestDelegate next, string[] headerNames, IHeaderConfig headerConfig)
{
_next = next;
_headerName = headerName;
_headerNames = headerNames;
_headerConfig = headerConfig;
}
public async Task Invoke(HttpContext context)
{
var expectedValue = await _headerConfig.GetExpectedHeaderValueAsync(_headerName);
bool valid = false;
if (!context.Request.Headers.TryGetValue(_headerName,out var headerValue) || string.IsNullOrWhiteSpace(headerValue))
// if (!context.Request.Headers.ContainsKey(_headerName) || string.IsNullOrWhiteSpace(context.Request.Headers[_headerName]))
foreach (var header in _headerNames)
{
context.Response.StatusCode = StatusCodes.Status400BadRequest;
await context.Response.WriteAsync($"Missing or empty header: {_headerName}");
return;
if (!context.Request.Headers.TryGetValue(header, out var headerValue) &&
!string.IsNullOrWhiteSpace(headerValue))
// if (!context.Request.Headers.ContainsKey(_headerName) || string.IsNullOrWhiteSpace(context.Request.Headers[_headerName]))
{
var expectedValue = await _headerConfig.GetExpectedHeaderValueAsync(header);
if (headerValue == expectedValue)
{
valid = true;
break;
}
// context.Response.StatusCode = StatusCodes.Status400BadRequest;
// await context.Response.WriteAsync($"Missing or empty header: {headerName}");
// return;
}
}
if (headerValue != expectedValue)
if (!valid)
{
context.Response.StatusCode = StatusCodes.Status401Unauthorized;
await context.Response.WriteAsync($"Invalid header value");
return;
}
// if (headerValue != expectedValue)
// {
// context.Response.StatusCode = StatusCodes.Status401Unauthorized;
// await context.Response.WriteAsync($"Invalid header value");
// return;
// }
//
// }
await _next(context);
}
}