AcaMate_API/Program/Common/Auth/APIHeaderMiddle.cs

84 lines
2.6 KiB
C#

using System.Threading.Tasks;
using AcaMate.Common.Data;
using Microsoft.AspNetCore.Http;
using Microsoft.EntityFrameworkCore;
namespace AcaMate.Common.Token;
public interface IHeaderConfig
{
Task<string> GetExpectedHeaderValueAsync(string headerName);
}
public class HeaderConfigRepository : IHeaderConfig
{
private readonly AppDbContext _dbContext;
public HeaderConfigRepository(AppDbContext dbContext)
{
_dbContext = dbContext;
}
public async Task<string> GetExpectedHeaderValueAsync(string headerName)
{
// 예를 들어, HeaderConfig 테이블에 헤더 이름과 기대 값이 저장되어 있다고 가정합니다.
var config = await _dbContext.APIHeader.
FirstOrDefaultAsync(h => h.h_key == headerName);
return config?.h_value ?? string.Empty;
}
}
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;
_headerConfig = headerConfig;
}
public async Task Invoke(HttpContext context)
{
bool valid = false;
foreach (var header in _headerNames)
{
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 (!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);
}
}