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.
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:
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:
public class CallerSetting
Let’s assume we have a controller, which handles the API requests, like this:
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:
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 (
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.
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...