├── .github └── FUNDING.yml ├── .gitignore ├── IP-SafeList-Demo.sln ├── LICENSE.md ├── MyWebApp.IntegrationTests ├── CustomRemoteIpAddressMiddleware.cs ├── IpRestrictionTests.cs └── MyWebApp.IntegrationTests.csproj ├── MyWebApp ├── Controllers │ └── ValuesController.cs ├── Infrastructure │ ├── AdminSafeListMiddleware.cs │ └── ClientIpCheckActionFilter.cs ├── MyWebApp.csproj ├── Program.cs ├── Properties │ └── launchSettings.json ├── Startup.cs ├── appsettings.Development.json └── appsettings.json ├── README.md └── images ├── IP-restriction-API-Swagger_UI.png ├── ip-safelist.png └── ngrok-powershell.png /.github/FUNDING.yml: -------------------------------------------------------------------------------- 1 | # These are supported funding model platforms 2 | 3 | github: # Replace with up to 4 GitHub Sponsors-enabled usernames e.g., [user1, user2] 4 | patreon: # Replace with a single Patreon username 5 | open_collective: # Replace with a single Open Collective username 6 | ko_fi: changhuixu 7 | tidelift: # Replace with a single Tidelift platform-name/package-name e.g., npm/babel 8 | community_bridge: # Replace with a single Community Bridge project-name e.g., cloud-foundry 9 | liberapay: # Replace with a single Liberapay username 10 | issuehunt: # Replace with a single IssueHunt username 11 | otechie: # Replace with a single Otechie username 12 | custom: # Replace with up to 4 custom sponsorship URLs e.g., ['link1', 'link2'] 13 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | ## Ignore Visual Studio temporary files, build results, and 2 | ## files generated by popular Visual Studio add-ons. 3 | ## 4 | ## Get latest from https://github.com/github/gitignore/blob/master/VisualStudio.gitignore 5 | 6 | # User-specific files 7 | *.rsuser 8 | *.suo 9 | *.user 10 | *.userosscache 11 | *.sln.docstates 12 | 13 | # User-specific files (MonoDevelop/Xamarin Studio) 14 | *.userprefs 15 | 16 | # Mono auto generated files 17 | mono_crash.* 18 | 19 | # Build results 20 | [Dd]ebug/ 21 | [Dd]ebugPublic/ 22 | [Rr]elease/ 23 | [Rr]eleases/ 24 | x64/ 25 | x86/ 26 | [Aa][Rr][Mm]/ 27 | [Aa][Rr][Mm]64/ 28 | bld/ 29 | [Bb]in/ 30 | [Oo]bj/ 31 | [Ll]og/ 32 | 33 | # Visual Studio 2015/2017 cache/options directory 34 | .vs/ 35 | # Uncomment if you have tasks that create the project's static files in wwwroot 36 | #wwwroot/ 37 | 38 | # Visual Studio 2017 auto generated files 39 | Generated\ Files/ 40 | 41 | # MSTest test Results 42 | [Tt]est[Rr]esult*/ 43 | [Bb]uild[Ll]og.* 44 | 45 | # NUnit 46 | *.VisualState.xml 47 | TestResult.xml 48 | nunit-*.xml 49 | 50 | # Build Results of an ATL Project 51 | [Dd]ebugPS/ 52 | [Rr]eleasePS/ 53 | dlldata.c 54 | 55 | # Benchmark Results 56 | BenchmarkDotNet.Artifacts/ 57 | 58 | # .NET Core 59 | project.lock.json 60 | project.fragment.lock.json 61 | artifacts/ 62 | 63 | # StyleCop 64 | StyleCopReport.xml 65 | 66 | # Files built by Visual Studio 67 | *_i.c 68 | *_p.c 69 | *_h.h 70 | *.ilk 71 | *.meta 72 | *.obj 73 | *.iobj 74 | *.pch 75 | *.pdb 76 | *.ipdb 77 | *.pgc 78 | *.pgd 79 | *.rsp 80 | *.sbr 81 | *.tlb 82 | *.tli 83 | *.tlh 84 | *.tmp 85 | *.tmp_proj 86 | *_wpftmp.csproj 87 | *.log 88 | *.vspscc 89 | *.vssscc 90 | .builds 91 | *.pidb 92 | *.svclog 93 | *.scc 94 | 95 | # Chutzpah Test files 96 | _Chutzpah* 97 | 98 | # Visual C++ cache files 99 | ipch/ 100 | *.aps 101 | *.ncb 102 | *.opendb 103 | *.opensdf 104 | *.sdf 105 | *.cachefile 106 | *.VC.db 107 | *.VC.VC.opendb 108 | 109 | # Visual Studio profiler 110 | *.psess 111 | *.vsp 112 | *.vspx 113 | *.sap 114 | 115 | # Visual Studio Trace Files 116 | *.e2e 117 | 118 | # TFS 2012 Local Workspace 119 | $tf/ 120 | 121 | # Guidance Automation Toolkit 122 | *.gpState 123 | 124 | # ReSharper is a .NET coding add-in 125 | _ReSharper*/ 126 | *.[Rr]e[Ss]harper 127 | *.DotSettings.user 128 | 129 | # JustCode is a .NET coding add-in 130 | .JustCode 131 | 132 | # TeamCity is a build add-in 133 | _TeamCity* 134 | 135 | # DotCover is a Code Coverage Tool 136 | *.dotCover 137 | 138 | # AxoCover is a Code Coverage Tool 139 | .axoCover/* 140 | !.axoCover/settings.json 141 | 142 | # Visual Studio code coverage results 143 | *.coverage 144 | *.coveragexml 145 | 146 | # NCrunch 147 | _NCrunch_* 148 | .*crunch*.local.xml 149 | nCrunchTemp_* 150 | 151 | # MightyMoose 152 | *.mm.* 153 | AutoTest.Net/ 154 | 155 | # Web workbench (sass) 156 | .sass-cache/ 157 | 158 | # Installshield output folder 159 | [Ee]xpress/ 160 | 161 | # DocProject is a documentation generator add-in 162 | DocProject/buildhelp/ 163 | DocProject/Help/*.HxT 164 | DocProject/Help/*.HxC 165 | DocProject/Help/*.hhc 166 | DocProject/Help/*.hhk 167 | DocProject/Help/*.hhp 168 | DocProject/Help/Html2 169 | DocProject/Help/html 170 | 171 | # Click-Once directory 172 | publish/ 173 | 174 | # Publish Web Output 175 | *.[Pp]ublish.xml 176 | *.azurePubxml 177 | # Note: Comment the next line if you want to checkin your web deploy settings, 178 | # but database connection strings (with potential passwords) will be unencrypted 179 | *.pubxml 180 | *.publishproj 181 | 182 | # Microsoft Azure Web App publish settings. Comment the next line if you want to 183 | # checkin your Azure Web App publish settings, but sensitive information contained 184 | # in these scripts will be unencrypted 185 | PublishScripts/ 186 | 187 | # NuGet Packages 188 | *.nupkg 189 | # NuGet Symbol Packages 190 | *.snupkg 191 | # The packages folder can be ignored because of Package Restore 192 | **/[Pp]ackages/* 193 | # except build/, which is used as an MSBuild target. 194 | !**/[Pp]ackages/build/ 195 | # Uncomment if necessary however generally it will be regenerated when needed 196 | #!**/[Pp]ackages/repositories.config 197 | # NuGet v3's project.json files produces more ignorable files 198 | *.nuget.props 199 | *.nuget.targets 200 | 201 | # Microsoft Azure Build Output 202 | csx/ 203 | *.build.csdef 204 | 205 | # Microsoft Azure Emulator 206 | ecf/ 207 | rcf/ 208 | 209 | # Windows Store app package directories and files 210 | AppPackages/ 211 | BundleArtifacts/ 212 | Package.StoreAssociation.xml 213 | _pkginfo.txt 214 | *.appx 215 | *.appxbundle 216 | *.appxupload 217 | 218 | # Visual Studio cache files 219 | # files ending in .cache can be ignored 220 | *.[Cc]ache 221 | # but keep track of directories ending in .cache 222 | !?*.[Cc]ache/ 223 | 224 | # Others 225 | ClientBin/ 226 | ~$* 227 | *~ 228 | *.dbmdl 229 | *.dbproj.schemaview 230 | *.jfm 231 | *.pfx 232 | *.publishsettings 233 | orleans.codegen.cs 234 | 235 | # Including strong name files can present a security risk 236 | # (https://github.com/github/gitignore/pull/2483#issue-259490424) 237 | #*.snk 238 | 239 | # Since there are multiple workflows, uncomment next line to ignore bower_components 240 | # (https://github.com/github/gitignore/pull/1529#issuecomment-104372622) 241 | #bower_components/ 242 | 243 | # RIA/Silverlight projects 244 | Generated_Code/ 245 | 246 | # Backup & report files from converting an old project file 247 | # to a newer Visual Studio version. Backup files are not needed, 248 | # because we have git ;-) 249 | _UpgradeReport_Files/ 250 | Backup*/ 251 | UpgradeLog*.XML 252 | UpgradeLog*.htm 253 | ServiceFabricBackup/ 254 | *.rptproj.bak 255 | 256 | # SQL Server files 257 | *.mdf 258 | *.ldf 259 | *.ndf 260 | 261 | # Business Intelligence projects 262 | *.rdl.data 263 | *.bim.layout 264 | *.bim_*.settings 265 | *.rptproj.rsuser 266 | *- [Bb]ackup.rdl 267 | *- [Bb]ackup ([0-9]).rdl 268 | *- [Bb]ackup ([0-9][0-9]).rdl 269 | 270 | # Microsoft Fakes 271 | FakesAssemblies/ 272 | 273 | # GhostDoc plugin setting file 274 | *.GhostDoc.xml 275 | 276 | # Node.js Tools for Visual Studio 277 | .ntvs_analysis.dat 278 | node_modules/ 279 | 280 | # Visual Studio 6 build log 281 | *.plg 282 | 283 | # Visual Studio 6 workspace options file 284 | *.opt 285 | 286 | # Visual Studio 6 auto-generated workspace file (contains which files were open etc.) 287 | *.vbw 288 | 289 | # Visual Studio LightSwitch build output 290 | **/*.HTMLClient/GeneratedArtifacts 291 | **/*.DesktopClient/GeneratedArtifacts 292 | **/*.DesktopClient/ModelManifest.xml 293 | **/*.Server/GeneratedArtifacts 294 | **/*.Server/ModelManifest.xml 295 | _Pvt_Extensions 296 | 297 | # Paket dependency manager 298 | .paket/paket.exe 299 | paket-files/ 300 | 301 | # FAKE - F# Make 302 | .fake/ 303 | 304 | # CodeRush personal settings 305 | .cr/personal 306 | 307 | # Python Tools for Visual Studio (PTVS) 308 | __pycache__/ 309 | *.pyc 310 | 311 | # Cake - Uncomment if you are using it 312 | # tools/** 313 | # !tools/packages.config 314 | 315 | # Tabs Studio 316 | *.tss 317 | 318 | # Telerik's JustMock configuration file 319 | *.jmconfig 320 | 321 | # BizTalk build output 322 | *.btp.cs 323 | *.btm.cs 324 | *.odx.cs 325 | *.xsd.cs 326 | 327 | # OpenCover UI analysis results 328 | OpenCover/ 329 | 330 | # Azure Stream Analytics local run output 331 | ASALocalRun/ 332 | 333 | # MSBuild Binary and Structured Log 334 | *.binlog 335 | 336 | # NVidia Nsight GPU debugger configuration file 337 | *.nvuser 338 | 339 | # MFractors (Xamarin productivity tool) working folder 340 | .mfractor/ 341 | 342 | # Local History for Visual Studio 343 | .localhistory/ 344 | 345 | # BeatPulse healthcheck temp database 346 | healthchecksdb 347 | 348 | # Backup folder for Package Reference Convert tool in Visual Studio 2017 349 | MigrationBackup/ 350 | -------------------------------------------------------------------------------- /IP-SafeList-Demo.sln: -------------------------------------------------------------------------------- 1 |  2 | Microsoft Visual Studio Solution File, Format Version 12.00 3 | # Visual Studio Version 16 4 | VisualStudioVersion = 16.0.30907.101 5 | MinimumVisualStudioVersion = 15.0.26124.0 6 | Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "MyWebApp", "MyWebApp\MyWebApp.csproj", "{CE338907-AE94-4387-BE97-A1B7591A0B50}" 7 | EndProject 8 | Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "MyWebApp.IntegrationTests", "MyWebApp.IntegrationTests\MyWebApp.IntegrationTests.csproj", "{6213C3D4-44D6-42C2-A57C-52ADF0C21165}" 9 | EndProject 10 | Global 11 | GlobalSection(SolutionConfigurationPlatforms) = preSolution 12 | Debug|Any CPU = Debug|Any CPU 13 | Debug|x64 = Debug|x64 14 | Debug|x86 = Debug|x86 15 | Release|Any CPU = Release|Any CPU 16 | Release|x64 = Release|x64 17 | Release|x86 = Release|x86 18 | EndGlobalSection 19 | GlobalSection(ProjectConfigurationPlatforms) = postSolution 20 | {CE338907-AE94-4387-BE97-A1B7591A0B50}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 21 | {CE338907-AE94-4387-BE97-A1B7591A0B50}.Debug|Any CPU.Build.0 = Debug|Any CPU 22 | {CE338907-AE94-4387-BE97-A1B7591A0B50}.Debug|x64.ActiveCfg = Debug|Any CPU 23 | {CE338907-AE94-4387-BE97-A1B7591A0B50}.Debug|x64.Build.0 = Debug|Any CPU 24 | {CE338907-AE94-4387-BE97-A1B7591A0B50}.Debug|x86.ActiveCfg = Debug|Any CPU 25 | {CE338907-AE94-4387-BE97-A1B7591A0B50}.Debug|x86.Build.0 = Debug|Any CPU 26 | {CE338907-AE94-4387-BE97-A1B7591A0B50}.Release|Any CPU.ActiveCfg = Release|Any CPU 27 | {CE338907-AE94-4387-BE97-A1B7591A0B50}.Release|Any CPU.Build.0 = Release|Any CPU 28 | {CE338907-AE94-4387-BE97-A1B7591A0B50}.Release|x64.ActiveCfg = Release|Any CPU 29 | {CE338907-AE94-4387-BE97-A1B7591A0B50}.Release|x64.Build.0 = Release|Any CPU 30 | {CE338907-AE94-4387-BE97-A1B7591A0B50}.Release|x86.ActiveCfg = Release|Any CPU 31 | {CE338907-AE94-4387-BE97-A1B7591A0B50}.Release|x86.Build.0 = Release|Any CPU 32 | {6213C3D4-44D6-42C2-A57C-52ADF0C21165}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 33 | {6213C3D4-44D6-42C2-A57C-52ADF0C21165}.Debug|Any CPU.Build.0 = Debug|Any CPU 34 | {6213C3D4-44D6-42C2-A57C-52ADF0C21165}.Debug|x64.ActiveCfg = Debug|Any CPU 35 | {6213C3D4-44D6-42C2-A57C-52ADF0C21165}.Debug|x64.Build.0 = Debug|Any CPU 36 | {6213C3D4-44D6-42C2-A57C-52ADF0C21165}.Debug|x86.ActiveCfg = Debug|Any CPU 37 | {6213C3D4-44D6-42C2-A57C-52ADF0C21165}.Debug|x86.Build.0 = Debug|Any CPU 38 | {6213C3D4-44D6-42C2-A57C-52ADF0C21165}.Release|Any CPU.ActiveCfg = Release|Any CPU 39 | {6213C3D4-44D6-42C2-A57C-52ADF0C21165}.Release|Any CPU.Build.0 = Release|Any CPU 40 | {6213C3D4-44D6-42C2-A57C-52ADF0C21165}.Release|x64.ActiveCfg = Release|Any CPU 41 | {6213C3D4-44D6-42C2-A57C-52ADF0C21165}.Release|x64.Build.0 = Release|Any CPU 42 | {6213C3D4-44D6-42C2-A57C-52ADF0C21165}.Release|x86.ActiveCfg = Release|Any CPU 43 | {6213C3D4-44D6-42C2-A57C-52ADF0C21165}.Release|x86.Build.0 = Release|Any CPU 44 | EndGlobalSection 45 | GlobalSection(SolutionProperties) = preSolution 46 | HideSolutionNode = FALSE 47 | EndGlobalSection 48 | GlobalSection(ExtensibilityGlobals) = postSolution 49 | SolutionGuid = {634683D5-84D1-470B-92ED-8F4AD69EABED} 50 | EndGlobalSection 51 | EndGlobal 52 | -------------------------------------------------------------------------------- /LICENSE.md: -------------------------------------------------------------------------------- 1 | 2 | The MIT License (MIT) 3 | 4 | Copyright (c) 2021 Changhui Xu 5 | 6 | Permission is hereby granted, free of charge, to any person obtaining a copy 7 | of this software and associated documentation files (the "Software"), to deal 8 | in the Software without restriction, including without limitation the rights 9 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 10 | copies of the Software, and to permit persons to whom the Software is 11 | furnished to do so, subject to the following conditions: 12 | 13 | The above copyright notice and this permission notice shall be included in all 14 | copies or substantial portions of the Software. 15 | 16 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 17 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 18 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 19 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 20 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 21 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 22 | SOFTWARE. 23 | -------------------------------------------------------------------------------- /MyWebApp.IntegrationTests/CustomRemoteIpAddressMiddleware.cs: -------------------------------------------------------------------------------- 1 | using System.Net; 2 | using Microsoft.AspNetCore.Builder; 3 | using Microsoft.AspNetCore.Hosting; 4 | using Microsoft.AspNetCore.Http; 5 | 6 | namespace MyWebApp.IntegrationTests; 7 | 8 | public class CustomRemoteIpAddressMiddleware(RequestDelegate next, IPAddress? fakeIpAddress = null) 9 | { 10 | private readonly IPAddress _fakeIpAddress = fakeIpAddress ?? IPAddress.Parse("127.0.0.1"); 11 | 12 | public async Task Invoke(HttpContext httpContext) 13 | { 14 | httpContext.Connection.RemoteIpAddress = _fakeIpAddress; 15 | await next(httpContext); 16 | } 17 | } 18 | 19 | public class CustomRemoteIpStartupFilter(IPAddress? remoteIp = null) : IStartupFilter 20 | { 21 | public Action Configure(Action next) 22 | { 23 | return app => 24 | { 25 | app.UseMiddleware(remoteIp); 26 | next(app); 27 | }; 28 | } 29 | } -------------------------------------------------------------------------------- /MyWebApp.IntegrationTests/IpRestrictionTests.cs: -------------------------------------------------------------------------------- 1 | using System.Net; 2 | using Microsoft.AspNetCore.Hosting; 3 | using Microsoft.AspNetCore.Http; 4 | using Microsoft.AspNetCore.Mvc.Testing; 5 | using Microsoft.AspNetCore.TestHost; 6 | using Microsoft.Extensions.DependencyInjection; 7 | using Microsoft.Extensions.Logging; 8 | using Microsoft.VisualStudio.TestTools.UnitTesting; 9 | 10 | namespace MyWebApp.IntegrationTests; 11 | 12 | [TestClass] 13 | public class IpRestrictionTests 14 | { 15 | [TestMethod] 16 | public void ParseConfigurations() 17 | { 18 | var b = IPNetwork.TryParse("2001:0db8::/64", out var ip); 19 | Assert.IsTrue(b); 20 | Assert.AreEqual(new IPNetwork(IPAddress.Parse("2001:0db8::"), 64), ip); 21 | } 22 | 23 | [TestMethod] 24 | public async Task HttpRequestWithAllowedIpAddressShouldReturn200() 25 | { 26 | var factory = new WebApplicationFactory().WithWebHostBuilder(builder => 27 | { 28 | builder.UseSetting("https_port", "5001").ConfigureLogging(c => c.AddConsole()); 29 | builder.ConfigureTestServices(services => 30 | { 31 | services.AddSingleton(new CustomRemoteIpStartupFilter(IPAddress.Parse("127.0.0.1"))); 32 | }); 33 | }); 34 | var client = factory.CreateClient(); 35 | var response = await client.GetAsync("values"); 36 | 37 | Assert.AreEqual(HttpStatusCode.OK, response.StatusCode); 38 | Assert.AreEqual("application/json; charset=utf-8", response.Content.Headers.ContentType?.ToString()); 39 | 40 | var json = await response.Content.ReadAsStringAsync(); 41 | Assert.AreEqual("[\"value1\",\"value2\"]", json); 42 | } 43 | 44 | [TestMethod] 45 | public async Task HttpRequestWithForbiddenIpAddressShouldReturn403() 46 | { 47 | var factory = new WebApplicationFactory().WithWebHostBuilder(builder => 48 | { 49 | builder.UseSetting("https_port", "5001").ConfigureLogging(c => c.AddConsole()); 50 | builder.ConfigureTestServices(services => 51 | { 52 | services.AddSingleton(new CustomRemoteIpStartupFilter(IPAddress.Parse("127.168.1.32"))); 53 | }); 54 | }); 55 | var client = factory.CreateClient(); 56 | var response = await client.GetAsync("values"); 57 | 58 | Assert.AreEqual(HttpStatusCode.Forbidden, response.StatusCode); 59 | } 60 | 61 | [TestMethod] 62 | public async Task HttpRequestWithLocalHostIpAddressShouldReturn200() 63 | { 64 | var factory = new WebApplicationFactory() 65 | .WithWebHostBuilder(builder => builder.UseSetting("https_port", "5001").ConfigureLogging(c => c.AddConsole())); 66 | 67 | var context = await factory.Server.SendAsync((c) => 68 | { 69 | c.Connection.RemoteIpAddress = IPAddress.Parse("127.168.1.32"); 70 | c.Request.Method = HttpMethods.Get; 71 | c.Request.Path = new PathString("/values"); 72 | c.Request.IsHttps = true; 73 | 74 | }); 75 | Assert.AreEqual((int)HttpStatusCode.Forbidden, context.Response.StatusCode); 76 | 77 | context = await factory.Server.SendAsync((c) => 78 | { 79 | c.Connection.RemoteIpAddress = IPAddress.Parse("192.168.1.9"); 80 | c.Request.Method = HttpMethods.Get; 81 | c.Request.Path = new PathString("/values"); 82 | c.Request.IsHttps = true; 83 | 84 | }); 85 | var response = context.Response; 86 | Assert.AreEqual((int)HttpStatusCode.OK, response.StatusCode); 87 | Assert.AreEqual("application/json; charset=utf-8", response.ContentType); 88 | 89 | using var sr = new StreamReader(response.Body); 90 | var json = await sr.ReadToEndAsync(); 91 | Assert.AreEqual("[\"value1\",\"value2\"]", json); 92 | } 93 | } -------------------------------------------------------------------------------- /MyWebApp.IntegrationTests/MyWebApp.IntegrationTests.csproj: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | net8.0 5 | false 6 | enable 7 | enable 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | -------------------------------------------------------------------------------- /MyWebApp/Controllers/ValuesController.cs: -------------------------------------------------------------------------------- 1 | using Microsoft.AspNetCore.Mvc; 2 | using MyWebApp.Infrastructure; 3 | 4 | namespace MyWebApp.Controllers; 5 | 6 | [ApiController] 7 | [Route("[controller]")] 8 | public class ValuesController(ILogger logger) : ControllerBase 9 | { 10 | [ServiceFilter(typeof(ClientIpCheckActionFilter))] 11 | [HttpGet] 12 | public IEnumerable Get() 13 | { 14 | logger.LogInformation("Client IP: {remoteIpAddress}", HttpContext.Connection.RemoteIpAddress?.ToString()); 15 | return new[] { "value1", "value2" }; 16 | } 17 | } -------------------------------------------------------------------------------- /MyWebApp/Infrastructure/AdminSafeListMiddleware.cs: -------------------------------------------------------------------------------- 1 | namespace MyWebApp.Infrastructure 2 | { 3 | public class AdminSafeListMiddleware( 4 | RequestDelegate next, 5 | ILogger logger, 6 | IpSafeList safeList) 7 | { 8 | public Task Invoke(HttpContext context) 9 | { 10 | var remoteIp = context.Connection.RemoteIpAddress; 11 | if (remoteIp == null) 12 | { 13 | throw new ArgumentException("Remote IP is NULL, may due to missing ForwardedHeaders."); 14 | } 15 | logger.LogDebug("Remote IpAddress: {RemoteIp}", remoteIp); 16 | 17 | if (remoteIp.IsIPv4MappedToIPv6) 18 | { 19 | remoteIp = remoteIp.MapToIPv4(); 20 | } 21 | 22 | if (!safeList.IsSafeIp(remoteIp)) 23 | { 24 | logger.LogWarning("Forbidden Request from IP: {remoteIp}", remoteIp); 25 | context.Response.StatusCode = StatusCodes.Status403Forbidden; 26 | return Task.CompletedTask; 27 | } 28 | 29 | return next.Invoke(context); 30 | } 31 | } 32 | } 33 | -------------------------------------------------------------------------------- /MyWebApp/Infrastructure/ClientIpCheckActionFilter.cs: -------------------------------------------------------------------------------- 1 | using System.Net; 2 | using Microsoft.AspNetCore.Mvc; 3 | using Microsoft.AspNetCore.Mvc.Filters; 4 | 5 | namespace MyWebApp.Infrastructure; 6 | 7 | public class ClientIpCheckActionFilter(IpSafeList safeList, ILogger logger) 8 | : ActionFilterAttribute 9 | { 10 | public override void OnActionExecuting(ActionExecutingContext context) 11 | { 12 | var remoteIp = context.HttpContext.Connection.RemoteIpAddress; 13 | if (remoteIp == null) 14 | { 15 | throw new ArgumentException("Remote IP is NULL, may due to missing ForwardedHeaders."); 16 | } 17 | logger.LogDebug("Remote IpAddress: {RemoteIp}", remoteIp); 18 | 19 | if (remoteIp.IsIPv4MappedToIPv6) 20 | { 21 | remoteIp = remoteIp.MapToIPv4(); 22 | } 23 | 24 | if (!safeList.IsSafeIp(remoteIp)) 25 | { 26 | logger.LogWarning("Forbidden Request from IP: {remoteIp}", remoteIp); 27 | context.Result = new StatusCodeResult(StatusCodes.Status403Forbidden); 28 | return; 29 | } 30 | 31 | base.OnActionExecuting(context); 32 | } 33 | } 34 | 35 | public class IpSafeList 36 | { 37 | private readonly List _safeIpAddresses; 38 | 39 | private readonly List _safeIpNetworks; 40 | 41 | public IpSafeList(string? ipAddresses, string? ipNetworks ) 42 | { 43 | if (string.IsNullOrWhiteSpace(ipAddresses)) 44 | { 45 | _safeIpAddresses = []; 46 | } 47 | else 48 | { 49 | _safeIpAddresses = ipAddresses.Split(';') 50 | .Where(x => !string.IsNullOrWhiteSpace(x)) 51 | .Select(IPAddress.Parse).ToList(); 52 | } 53 | 54 | _safeIpNetworks = []; 55 | 56 | foreach (var i in (ipNetworks??string.Empty).Split(';')) 57 | { 58 | if (IPNetwork.TryParse(i, out var ip)) 59 | { 60 | _safeIpNetworks.Add(ip); 61 | } 62 | else 63 | { 64 | 65 | } 66 | } 67 | } 68 | 69 | public bool IsSafeIp(IPAddress remoteIp) => _safeIpAddresses.Contains(remoteIp) || _safeIpNetworks.Any(x => x.Contains(remoteIp)); 70 | } 71 | -------------------------------------------------------------------------------- /MyWebApp/MyWebApp.csproj: -------------------------------------------------------------------------------- 1 |  2 | 3 | 4 | net8.0 5 | enable 6 | enable 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | -------------------------------------------------------------------------------- /MyWebApp/Program.cs: -------------------------------------------------------------------------------- 1 | namespace MyWebApp; 2 | 3 | public class Program 4 | { 5 | public static void Main(string[] args) 6 | { 7 | CreateHostBuilder(args).Build().Run(); 8 | } 9 | 10 | public static IHostBuilder CreateHostBuilder(string[] args) => 11 | Host.CreateDefaultBuilder(args) 12 | .ConfigureWebHostDefaults(webBuilder => 13 | { 14 | webBuilder.UseStartup(); 15 | }); 16 | } -------------------------------------------------------------------------------- /MyWebApp/Properties/launchSettings.json: -------------------------------------------------------------------------------- 1 | { 2 | "$schema": "http://json.schemastore.org/launchsettings.json", 3 | "iisSettings": { 4 | "windowsAuthentication": false, 5 | "anonymousAuthentication": true, 6 | "iisExpress": { 7 | "applicationUrl": "http://localhost:53971", 8 | "sslPort": 44300 9 | } 10 | }, 11 | "profiles": { 12 | "IIS Express": { 13 | "commandName": "IISExpress", 14 | "launchBrowser": true, 15 | "launchUrl": "swagger", 16 | "environmentVariables": { 17 | "ASPNETCORE_ENVIRONMENT": "Development" 18 | } 19 | }, 20 | "MyWebApp": { 21 | "commandName": "Project", 22 | "dotnetRunMessages": "true", 23 | "launchBrowser": true, 24 | "launchUrl": "swagger", 25 | "applicationUrl": "https://localhost:5001;http://localhost:5000", 26 | "environmentVariables": { 27 | "ASPNETCORE_ENVIRONMENT": "Development" 28 | } 29 | } 30 | } 31 | } 32 | -------------------------------------------------------------------------------- /MyWebApp/Startup.cs: -------------------------------------------------------------------------------- 1 | using Microsoft.AspNetCore.HttpOverrides; 2 | using Microsoft.OpenApi.Models; 3 | using MyWebApp.Infrastructure; 4 | 5 | namespace MyWebApp; 6 | 7 | public class Startup(IConfiguration configuration) 8 | { 9 | public IConfiguration Configuration { get; } = configuration; 10 | 11 | // This method gets called by the runtime. Use this method to add services to the container. 12 | public void ConfigureServices(IServiceCollection services) 13 | { 14 | services.AddControllers(); 15 | services.AddSwaggerGen(c => 16 | { 17 | c.SwaggerDoc("v1", new OpenApiInfo { Title = "MyWebApp", Version = "v1" }); 18 | }); 19 | 20 | var ipSafeList = new IpSafeList(Configuration.GetValue("IpSafeList:IpAddresses"), 21 | Configuration.GetValue("IpSafeList:IpNetworks")); 22 | services.AddSingleton(ipSafeList); 23 | services.AddScoped(); 24 | } 25 | 26 | // This method gets called by the runtime. Use this method to configure the HTTP request pipeline. 27 | public void Configure(IApplicationBuilder app, IWebHostEnvironment env) 28 | { 29 | //app.UseMiddleware(); 30 | 31 | if (env.IsDevelopment()) 32 | { 33 | app.UseDeveloperExceptionPage(); 34 | app.UseSwagger(); 35 | app.UseSwaggerUI(c => c.SwaggerEndpoint("/swagger/v1/swagger.json", "MyWebApp v1")); 36 | } 37 | 38 | app.UseHttpsRedirection(); 39 | app.UseForwardedHeaders(new ForwardedHeadersOptions 40 | { 41 | ForwardedHeaders = ForwardedHeaders.XForwardedFor | ForwardedHeaders.XForwardedProto 42 | }); 43 | 44 | app.UseRouting(); 45 | app.UseAuthorization(); 46 | 47 | app.UseEndpoints(endpoints => 48 | { 49 | endpoints.MapControllers(); 50 | }); 51 | } 52 | } -------------------------------------------------------------------------------- /MyWebApp/appsettings.Development.json: -------------------------------------------------------------------------------- 1 | { 2 | "Logging": { 3 | "LogLevel": { 4 | "Default": "Information", 5 | "Microsoft": "Warning", 6 | "Microsoft.Hosting.Lifetime": "Information" 7 | } 8 | } 9 | } 10 | -------------------------------------------------------------------------------- /MyWebApp/appsettings.json: -------------------------------------------------------------------------------- 1 | { 2 | "Logging": { 3 | "LogLevel": { 4 | "Default": "Information", 5 | "Microsoft": "Warning", 6 | "Microsoft.Hosting.Lifetime": "Information" 7 | } 8 | }, 9 | "AllowedHosts": "*", 10 | "IpSafeList": { 11 | "IpAddresses": "127.0.0.1;::1", 12 | "IpNetworks": "192.168.1.0/24;2001:0db8::/64;110.40.88.12/28" 13 | } 14 | } 15 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Implementing and Testing IP SafeList in ASP.NET Core Web API projects 2 | 3 | [![ko-fi](https://ko-fi.com/img/githubbutton_sm.svg)](https://ko-fi.com/I3I63W4OK) 4 | 5 | ## Medium Article 6 | 7 | [Implementing and Testing IP SafeLists in ASP.NET Core](https://codeburst.io/implementing-and-testing-ip-safelists-in-asp-net-core-dbd9e6f4b696) 8 | 9 | We sometimes want to limit our application to only certain IP addresses or IP network ranges. For example, during [beta testing](https://en.wikipedia.org/wiki/Software_testing), we prefer to only allow admins and limited testers to access the new website. Besides blocking the whole application, we sometimes want to expose most APIs in an application but restrict a few API endpoints to a confined network so that sensitive data won't be scraped. 10 | 11 | IP restrictions can be done at several levels to achieve security goals. As developers, we can properly guard applications and API endpoints in our code so that they are available to only a list of network addresses. The official tutorial, _[Client IP safelist for ASP.NET Core](https://docs.microsoft.com/en-us/aspnet/core/security/ip-safelist)_, has documented different ways to implement an IP address safelist (aka an allow list) in an ASP.NET Core app. 12 | 13 | In this article, we will go over some implementation details for allowing a list of IP addresses or CIDR blocks to access our API endpoints. We will use a NuGet package [IPNetwork2](https://www.nuget.org/packages/IPNetwork2/) to parse and check IP addresses and CIDR blocks. It's worth noting that the NuGet package [AzureIPNetworks](https://www.nuget.org/packages/AzureIPNetworks/) uses IPNetwork2 too. 14 | 15 | We will create a middleware and an Action filter. We will write integration tests to verify the request pipeline. In the end, I will show you how to use `ngrok` to test the application from other computers other than our dev machine. 16 | 17 | ## Testing with `ngrok` 18 | 19 | `ngrok` is a reverse proxy that creates a secure tunnel from a public endpoint to a locally running web service. 20 | 21 | Download `ngrok` from its official site [https://ngrok.com/](https://ngrok.com/). Then start the app from Visual Studio (or VS Code), and run the executable in a PowerShell terminal using the following command. 22 | 23 | ```powershell 24 | .\ngrok.exe http https://localhost:44300 -host-header="localhost:44300" 25 | ``` 26 | 27 | ![ngrok running in a PowerShell terminal](./images/ngrok-powershell.png) 28 | 29 | `ngrok` creates a public endpoint `https://6b995c1b2b60.ngrok.io` which enables people to visit the local instance `https://localhost:44300` in our development server. 30 | 31 | Therefore, we can visit the URL that is given by `ngrok` from another computer. In this example, the link is [https://6b995c1b2b60.ngrok.io/swagger/index.html](https://6b995c1b2b60.ngrok.io/swagger/index.html). Whereas your link will be slightly different. 32 | 33 | Try out the Swagger page, and you will get the results like below. 34 | 35 | ![API has IP restriction](./images/IP-restriction-API-Swagger_UI.png) 36 | 37 | You should see a `403` response if your IP address is not in the safe list. Otherwise, you should see a `200` response. 38 | 39 | ## License 40 | 41 | Feel free to use the code in this repository as it is under MIT license. 42 | 43 | [![ko-fi](https://ko-fi.com/img/githubbutton_sm.svg)](https://ko-fi.com/I3I63W4OK) 44 | -------------------------------------------------------------------------------- /images/IP-restriction-API-Swagger_UI.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/dotnet-labs/Client-IP-SafeList/3575eedea39a7e0ce2e24babc48f06b35ee9c8e0/images/IP-restriction-API-Swagger_UI.png -------------------------------------------------------------------------------- /images/ip-safelist.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/dotnet-labs/Client-IP-SafeList/3575eedea39a7e0ce2e24babc48f06b35ee9c8e0/images/ip-safelist.png -------------------------------------------------------------------------------- /images/ngrok-powershell.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/dotnet-labs/Client-IP-SafeList/3575eedea39a7e0ce2e24babc48f06b35ee9c8e0/images/ngrok-powershell.png --------------------------------------------------------------------------------