Implementing API Key Authentication in ASP.NET Core

Recently I was watching Nick Chapsas on YouTube and his tutorial on Implementing API Key Authentication in ASP.NET Core.  He did a very nice job of explaining how to add checking for a HTTP Header value to authenticate calls to your web api.  He touched on adding support for minimal endpoints in .NET core by creating a filter.  Specifically, a class ApiKeyEndpointFilter that will return TypedResults.Unauthorized if the x-api-key is missing or invalid.  This return type does not support a custom unauthorized message.  In order to accomplish that, a new class is needed that implements IResult and IStatusCodeHttpResult.  The class signature looks like: UnauthorizedHttpObjectResult : IResult, IStatusCodeHttpResult

Once you implement, you can then use the following approach to use the filter:

return new UnauthorizedHttpObjectResult("API Key missing"); 

app.MapGet("/", () => "Welcome mini!")
                .AddEndpointFilter<ApiKeyEndpointFilter>();

My full solution is available on GitHub:
https://github.com/cliffordru/ApiKeyAuthentication.git

See UnauthorizedHttpObjectResult.cs for the code needed to return a custom message. 

Tags: unauthorized http objectresult TypedResults with custom message

Need a developer, architect or manager? I am available - email me at [email protected]

Add comment