Client IP safelist for ASP.NET Core

What is client IP safe list technique

In this technique we track every request coming to our API and check its IP address, then we check list of our safe IP lists, if it exists in that list we allow it otherwise we don’t allow it to move on relevant controller.

Benefits of white listing IPs

This technique comes under security concerns, following are the benefits :

  • Enhanced security
  • Reduced attack surface
  • Prevention of unauthorized access

At which level of application we should restrict it

We can apply this restriction at three levels:

1/ Cloud level ( e.g. using azure services )

2/ Network level ( e.g. firewall )

3/ Application level ( that we are going to do )

The more higher you can go would be more appropriate unless you have some IF/ELSE that forces you to come at low level.

Fun fact : We can apply whitelisting technique via load balancer or rate limiter as well.

Enough talking let’s dive into code implementation.

Ways to whitelist IP it in .NET API

We have two ways to achieve it:

1/ Via Middleware ( I already wrote about middlewares )

2/ Via Action Filters ( Read a previous newsletter of mine on action filters )

Before moving on let’s add list of allowed IPs in appsetting Client IP safelist for ASP.NET Core

1/ Implementing via Middleware: So let’ add the middleware, whose code looks like this Client IP safelist for ASP.NET Core

And don’t forget to register the middleware Client IP safelist for ASP.NET Core

2/ Via Action Filter: Let’s create an action filter that looks like this : Client IP safelist for ASP.NET Core

Register action filter service: Client IP safelist for ASP.NET Core

Now we can apply this filter on any method in controller and even at controller level as well. Client IP safelist for ASP.NET Core

Find code of this newsletter issue at my GitHub Repo

This article was originally published at https://mwaseemzakir.substack.com/ on .

Whenever you're ready, there are 3 ways I can help you:

  1. Subscribe to my youtube channel : For in-depth tutorials, coding tips, and industry insights.
  2. Promote yourself to 9,000+ subscribers : By sponsoring this newsletter
  3. Patreon community : Get access to all of my blogs and articles at one place