Custom Caller Authentication with ASP.NET Core 5.0 Web API
Developing micro services with Microsoft ASP.NET Core 5.0 Web API is powerful and fun, but the fun stops, if your data are accesses unauthorized. It is absolutely fundamental to have a protection layer, which filters out unwanted data requests.
A common way is to limit the service access by providing API Keys to well known clients. In this post I will show you how to implement such a filter in terms of API keys and IP addresses.
The Settings
Lets start with the list of clients, who should be able to access the data. The most useful place for this is in the appsettings.json of the Core 5.0 Web API project:
1 | ... |
This list has two entries: one for the server itself (“localhost”), which is restricted to the local IP address "::1"
, and one for the test user "John Doe"
, who can access from any IP address ("*"
), but must supply his personal API key with his requests.
In order to handle this setting, we have to introduce it to the system at startup as a class:
1 | public class CallerSetting |
1 | ... |
The Controller
Let’s assume we have a controller, which handles the API requests, like this:
1 | using Microsoft.AspNetCore.Mvc; |
To prevent to write a request check against our new settings in each action method, we can decorate the whole controller class by introducing an new custom Attribute
, which will do the work:
1 | ... |
The Attribute
Here is the code for the new attribute. It uses the IActionFilter
. These filters run within the ASP.NET Core action invocation pipeline, in our case BEFORE the action is entered (OnActionExecutionAsync
).
1 | using Microsoft.AspNetCore.Mvc; |
The Result
More Info
- Microsoft Docs: Filters in ASP.NET Core
- Microsoft Docs: Configuration in ASP.NET Core
You can interact with this article (applause, criticism, whatever) by mention it in one of your posts, which will also be shown here as a Webmention ... or you leave a good old comment with your GitHub account.
Webmentions
No Webmentions yet...
In case your blog software can't send Webmentions, you can use this form to submit me a mention of this article...
Comments