41 lines
1.2 KiB
C#
41 lines
1.2 KiB
C#
using Microsoft.AspNetCore.Diagnostics;
|
|
using Microsoft.AspNetCore.Http.HttpResults;
|
|
using Microsoft.AspNetCore.Mvc;
|
|
using System.Net;
|
|
|
|
namespace PortBlog.API.Middleware
|
|
{
|
|
public class ApiKeyMiddleware
|
|
{
|
|
private readonly RequestDelegate _next;
|
|
private const string APIKEY = "XApiKey";
|
|
public ApiKeyMiddleware(RequestDelegate next)
|
|
{
|
|
_next = next;
|
|
}
|
|
|
|
public async Task InvokeAsync(HttpContext context)
|
|
{
|
|
if (!context.Request.Headers.TryGetValue(APIKEY, out var extractedApiKey))
|
|
{
|
|
context.Response.StatusCode = StatusCodes.Status401Unauthorized;
|
|
await context.Response.WriteAsync("Unauthorized client");
|
|
return;
|
|
}
|
|
|
|
var appSettings = context.RequestServices.GetRequiredService<IConfiguration>();
|
|
|
|
var apiKey = appSettings.GetValue<string>(APIKEY);
|
|
|
|
if (apiKey != null && !apiKey.Equals(extractedApiKey))
|
|
{
|
|
context.Response.StatusCode = StatusCodes.Status401Unauthorized;
|
|
await context.Response.WriteAsync("Unauthorized client");
|
|
return;
|
|
}
|
|
|
|
await _next(context);
|
|
}
|
|
}
|
|
}
|