forked from AcaMate/AcaMate_API
86 lines
2.4 KiB
C#
86 lines
2.4 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);
|
|
}
|
|
|
|
/// <summary>
|
|
/// DB에서 헤더 키값 찾아서 그 밸류 값 빼오기 위해서 사용
|
|
/// </summary>
|
|
public class HeaderConfigRepository : IHeaderConfig
|
|
{
|
|
private readonly AppDbContext _dbContext;
|
|
|
|
public HeaderConfigRepository(AppDbContext dbContext)
|
|
{
|
|
_dbContext = dbContext;
|
|
}
|
|
|
|
public async Task<string> GetExpectedHeaderValueAsync(string headerName)
|
|
{
|
|
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;
|
|
}
|
|
|
|
public async Task Invoke(HttpContext context)
|
|
{
|
|
|
|
if (context.Request.Path.StartsWithSegments("/api/v1/in/app", StringComparison.OrdinalIgnoreCase))
|
|
{
|
|
await _next(context);
|
|
return;
|
|
}
|
|
|
|
// Scoped 사용해서 값 가져오는 곳임
|
|
var headerConfig = context.RequestServices.GetRequiredService<IHeaderConfig>();
|
|
|
|
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 dbValue = await headerConfig.GetExpectedHeaderValueAsync(header);
|
|
if (headerValue == dbValue)
|
|
{
|
|
valid = true;
|
|
break;
|
|
}
|
|
}
|
|
}
|
|
|
|
if (!valid)
|
|
{
|
|
context.Response.StatusCode = StatusCodes.Status401Unauthorized;
|
|
await context.Response.WriteAsync($"Invalid header value");
|
|
return;
|
|
}
|
|
|
|
await _next(context);
|
|
}
|
|
} |