You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
58 lines
1.9 KiB
58 lines
1.9 KiB
using Microsoft.AspNetCore.Http;
|
|
using Microsoft.Extensions.Configuration;
|
|
using Microsoft.Extensions.DependencyInjection;
|
|
using System.Threading.Tasks;
|
|
|
|
namespace SecuringWebApiUsingApiKey.Middleware
|
|
{
|
|
public class ApiKeyMiddleware
|
|
{
|
|
private readonly RequestDelegate _next;
|
|
private const string APIKEYNAME = "ApiKey";
|
|
public ApiKeyMiddleware(RequestDelegate next)
|
|
{
|
|
_next = next;
|
|
}
|
|
public async Task InvokeAsync(HttpContext context)
|
|
{
|
|
var appSettings = context.RequestServices.GetRequiredService<IConfiguration>();
|
|
string apiCheck = appSettings.GetValue<string>("ApiCheck");
|
|
if (apiCheck == "e913aab4-c2c5-4e33-ad24-d25848f748e7")
|
|
{
|
|
await _next(context);
|
|
return;
|
|
|
|
}
|
|
if (!context.Request.Headers.TryGetValue(APIKEYNAME, out var extractedApiKey))
|
|
{
|
|
context.Response.StatusCode = 401;
|
|
await context.Response.WriteAsync("Api Key was not provided. (Using ApiKeyMiddleware) ");
|
|
return;
|
|
}
|
|
|
|
|
|
|
|
var apiKey = appSettings.GetValue<string>(APIKEYNAME);
|
|
string[] keys = apiKey.Split(",");
|
|
|
|
bool tokenok = false;
|
|
for (int i = 0; i < keys.Length; i++)
|
|
if (keys[i] == extractedApiKey)
|
|
{
|
|
tokenok = true;
|
|
break;
|
|
}
|
|
|
|
//if (!apiKey.Equals(extractedApiKey))
|
|
if (!tokenok)
|
|
{
|
|
context.Response.StatusCode = 401;
|
|
await context.Response.WriteAsync
|
|
("Unauthorized client. (Using ApiKeyMiddleware)");
|
|
return;
|
|
}
|
|
|
|
await _next(context);
|
|
}
|
|
}
|
|
} |