Need authentication from MVC to WebAPI
Hi all,
Can someone point me in the right direction here. I want to do something simple. I want to spin up a new .netcore8 solution. I'm going to have 2 stand-alone projects. A MVC and a WebAPI project. When deployed, both of these will be running in their own IIS instances.
I need to authorize the MVC app to talk to the WebAPI app. No identity server. No 3rd party stuff. (eg no Okta/AD or anything else)
This is going to be super simple, and a POC. I'm going to store the creds in each appSettings file.
Can someone point me in the right direction on either: a)A sample solution template or b)Which nuget packages do I need to install/explore? All my google searches are way to complicated for what I want to do. Thanks!
Can someone point me in the right direction on either: a)A sample solution template or b)Which nuget packages do I need to install/explore? All my google searches are way to complicated for what I want to do. Thanks!
4 Replies
Simplest solution sounds like just adding a global action filter that checks for a pre-determined header value, like a singular API key
That's what I did. After posting this question, and doing some searching on this channel, it pointed me in the right direction. Thanks for confirming!
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
GitHub
L2Proxy/L2Proxy/Auth/ApiKeyAttribute.cs at 7a5b321f2a9403188f74f78e...
A simple MITM Proxy for Lineage 2. Contribute to Elfocrash/L2Proxy development by creating an account on GitHub.
[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();
}
}