API Key Authentication in ASP .NET Core
Exciting News - YouTube Channel Launch : My YouTube Channel is live, featuring the first video on .NET Debugging Techniques in Visual Studio. Check it out and hit subscribe for more tech insights. Letβs embark on this learning journey together!
Authorization filters are used to implement authentication and authorization for controller actions.
For example, the Authorize filter is an example of an Authorization filter that we are going to see in action.
API Key Authentication
JWT authentication is commonly employed, but when dealing with third-party APIs, API Key Authentication could be helpful
In this method, a key is included with each request, establishing our legitimacy for making those calls. Typically, this key is transmitted in the headers.
How To Implement it in ASP.NET Core?
We can implement it by implementing IAuthorizationFilter available in Microsoft.AspNetCore.Mvc.Filters.
It has only one method which we need to implement :
void OnAuthorization(AuthorizationFilterContext context);
In the present scenario, assuming we possess an API key stored in our application settings ( although I will never recommend saving API Key in app setting, use whatever Vault mechanism you prefer to save them)
The task involves verifying this key against each incoming request to determine whether to grant or deny access.
So in our case our implementation would look like this :
public sealed class ApiKeyAuthorizationFilter : IAuthorizationFilter
{
public void OnAuthorization(AuthorizationFilterContext context)
{
var request = context.HttpContext.Request;
var providedApiKey = request.Headers["ApiKey"].FirstOrDefault();
var configuration = context.
HttpContext.
RequestServices.
GetRequiredService<IConfiguration>();
var apiKey = GetApiKey(configuration);
if (string.IsNullOrWhiteSpace(providedApiKey) || providedApiKey != apiKey)
{
context.Result = new UnauthorizedResult();
}
}
}
The next consideration is how to implement this on our controllers, enabling us to utilize it as an attribute for our controller or action methods.
To achieve this, we must modify our code by inheriting from the Attribute class.
public sealed class ApiKeyAuthorizationFilter : Attribute, IAuthorizationFilter
{
public void OnAuthorization(AuthorizationFilterContext context)
{
var request = context.HttpContext.Request;
var providedApiKey = request.Headers["ApiKey"].FirstOrDefault();
var configuration = context.HttpContext.RequestServices
.GetRequiredService<IConfiguration>();
var apiKey = GetApiKey(configuration);
if (string.IsNullOrWhiteSpace(providedApiKey) || providedApiKey != apiKey)
{
context.Result = new UnauthorizedResult();
}
}
}
That is all we need to do now we can apply it wherever we want :
-
Controllers
-
Action Method
Implementation looks like this :
[ApiController]
[Route("[controller]")]
public class StudentController : ControllerBase
{
[ApiKeyAuthorizationFilter]
[HttpGet]
public IActionResult Get()
{
return Ok("Hello from StudentController");
}
}
We can pass API-Key like this in header :
If key does not match then our filter will return un authorized result and it will not allow controller to execute further and on postman it will look like this :
Download the demo code from GitHub Repo
Whenever you're ready, there are 3 ways I can help you:
- Subscribe to my youtube channel : For in-depth tutorials, coding tips, and industry insights.
- Promote yourself to 9,000+ subscribers : By sponsoring this newsletter
- Patreon community : Get access to all of my blogs and articles at one place