IP Restrictions
Sometimes we need to limit from users to access to Web App by IP address, and this can be done by adding a Middleware to filtering the request.
Adding White List IP Address Config
First configure the whitelisted IP addresses in the appsettings.json by adding a new section called IpSecuritySettings
"IpSecuritySettings": {
"AllowedIPs": "::1,0.0.0.0,127.0.0.1" // comma-delimited list of whitelisted IP addresses, seperator ',' or ';'
}Add the IpSecuritySettings.cs for the configuration:
public class IpSecuritySettings
{
public string AllowedIPs { get; set; }
public string[] AllowedIPsList
{
get
{
return AllowedIPs
.Split(new Char[] { ',', ';' }, StringSplitOptions.RemoveEmptyEntries)
.Where(x => !string.IsNullOrWhiteSpace(x))
.Select(s => s.Trim())
.ToArray();
}
}
}Once you have added the IpSecuritySettings.cs, you will need to configure the options in the Startup.cs. Add the IpSecuritySettings in ConfigureServices with the Configure extension method:
Setup the middleware
Add a new file IpRestrictionMiddleware.cs to filtering the request which is not whitelisted IP addresses:
In the Startup.cs, add IpRestrictionMiddleware as the middleware in the pipeline in Configure with the UseMiddleware extension method:
Example
Last updated
Was this helpful?