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
1/ Implementing via Middleware: So let’ add the middleware, whose code looks like this
And don’t forget to register the middleware
2/ Via Action Filter: Let’s create an action filter that looks like this :
Register action filter service:
Now we can apply this filter on any method in controller and even at controller level as well.
Find code of this newsletter issue at my GitHub Repo
Whenever you're ready, there are 3 ways I can help you:
- Subscribe to my youtube channel : For in-depth tutorials, coding tips, and industry insights.
- Promote yourself to 9,000+ subscribers : By sponsoring this newsletter
- Patreon community : Get access to all of my blogs and articles at one place