AspNetCore.Docs/aspnetcore/security/ip-safelist.md

3.5 KiB

title author description ms.author ms.custom ms.date uid
Client IP safelist for ASP.NET Core damienbod Learn how to write Middleware or action filters to validate remote IP addresses against a list of approved IP addresses. tdykstra mvc 08/31/2018 security/ip-safelist

Client IP safelist for ASP.NET Core

By Damien Bowden and Tom Dykstra

This article shows three ways to implement an IP safelist (also known as a whitelist) in an ASP.NET Core app. You can use:

  • Middleware to check the remote IP address of every request.
  • Action filters to check the remote IP address of requests for specific controllers or action methods.
  • Razor Pages filters to check the remote IP address of requests for Razor pages.

The sample app illustrates both approaches. In each case, a string containing approved client IP addresses is stored in an app setting. The middleware or filter parses the string into a list and checks if the remote IP is in the list. If not, an HTTP 403 Forbidden status code is returned.

View or download sample code (how to download)

The safelist

The list is configured in the appsettings.json file. It's a semicolon-delimited list and can contain IPv4 and IPv6 addresses.

[!code-json]

Middleware

The Configure method adds the middleware and passes the safelist string to it in a constructor parameter.

[!code-csharp]

The middleware parses the string into an array and looks for the remote IP address in the array. If the remote IP address is not found, the middleware returns HTTP 401 Forbidden. This validation process is bypassed for HTTP Get requests.

[!code-csharp]

Action filter

If you want a safelist only for specific controllers or action methods, use an action filter. Here's an example:

[!code-csharp]

The action filter is added to the services container.

[!code-csharp]

The filter can then be used on a controller or action method.

[!code-csharp]

In the sample app, the filter is applied to the Get method. So when you test the app by sending a Get API request, the attribute is validating the client IP address. When you test by calling the API with any other HTTP method, the middleware is validating the client IP.

Razor Pages filter

If you want a safelist for a Razor Pages app, use a Razor Pages filter. Here's an example:

[!code-csharp]

This filter is enabled by adding it to the MVC Filters collection.

[!code-csharp]

When you run the app and request a Razor page, the Razor Pages filter is validating the client IP.

Next steps

Learn more about ASP.NET Core Middleware.