Setting up ApiKey-based Authentication in ASP.Net Core Web API
In this blog we will see how to develop a secure .NET Core Web API. Although there are many ways to secure the web API, but here we will talk about Apikey-based authentication.
First of all add below key in appsettings.json file of your .Net Core API project"APIKey": "MyAPIKey123"
Create a class to implement ApiKey based authentication
Add a class file within your project - APIKeyAuthAttribute.cs Code written in this class is mentioned below.[AttributeUsage(validOn:AttributeTargets.Class | AttributeTargets.Method)] public class APIKeyAuthAttribute : Attribute, IAsyncActionFilter { private const string ApiKeyHeader = "ApiKey"; public async Task OnActionExecutionAsync(ActionExecutingContext context, ActionExecutionDelegate next) { if(!context.HttpContext.Request.Headers.TryGetValue(ApiKeyHeader, out var potentialApiKey)) { context.Result = new UnauthorizedResult(); return; } var configuration = context.HttpContext.RequestServices.GetRequiredService<'IConfiguration>(); var apiKey = configuration.GetValue<'string'>(key:"ApiKey");//To read API key from appsettings.json use this line //var apiKey = "MyAPIKey123"; //To hard code the API key within your code, use this line if (!apiKey.Equals(potentialApiKey)) { context.Result = new UnauthorizedResult(); return; } await next(); } }Once your APIKeyAuthAttribute.cs file is ready. Go to your existing controller class or create a new controller class within your project. Decorate your controller class or action method within your controller class with below line -
Add attribute to controller class or action method to apply ApiKey based authentication
[APIKeyAuth]Below is the sample code.
[APIKeyAuth] public Task<'IActionResult'> GetEmployeeData([FromBody]object request) { try { //Write Code here return null; } catch (Exception ex) { throw; } }Now open postman or any client application you have installed in your computer. I am using POSTMAN to implement this scenario. Pass your API request data in body tab of Postman and ApiKey in headers tab.
Please see below screen shot.
Comments
Post a Comment
Dear Readers, Please post your valuable feedback in the comment section if you like this blog or if you have any suggestions. I would love to hear the same from you. Thanks