bwca
Need authentication from MVC to WebAPI
[AttributeUsage(AttributeTargets.Class)]
public class ApiKeyAttribute : Attribute, IAsyncActionFilter
{
private const string APIKEYNAME = "ApiKey";
public async Task OnActionExecutionAsync(ActionExecutingContext context, ActionExecutionDelegate next)
{
if (!context.HttpContext.Request.Headers.TryGetValue("x-api-key", out var extractedApiKey))
{
context.Result = new ContentResult()
{
StatusCode = 401,
Content = "Invalid API key"
};
return;
}
var appSettings = context.HttpContext.RequestServices.GetRequiredService<IConfiguration>();
var apiKey = appSettings.GetValue<string>("ApiSettings:ApiKey");
if (!apiKey.Equals(extractedApiKey))
{
context.Result = new ContentResult()
{
StatusCode = 401,
Content = "Invalid API key"
};
return;
}
await next();
}
}
5 replies
Need authentication from MVC to WebAPI
For completeness, in case anyone else is interested, I found this gem. (no idea who this is, but, it worked great)
https://github.com/Elfocrash/L2Proxy/blob/7a5b321f2a9403188f74f78ed9b9b72f7de565f1/L2Proxy/Auth/ApiKeyAttribute.cs
5 replies