2016-11-04 95 views
6

我想通过IP地址来限制一个站点。在以前版本的MVC我会添加类似如下的web.config中:Asp.Net核心IP安全

<security> 
    <ipSecurity allowUnlisted="false" denyAction="NotFound"> 
    <add allowed="true" ipAddress="XX.XX.XX.XX" subnetMask="255.255.255.0"/> 
    </ipSecurity> 
</security> 

但是,增加这一个AspNetCore项目会导致应用程序在启动时失败,出现错误

无法启动过程Web服务器请求失败,状态码为500,内部服务器错误

很明显,我打破了配置,因为它在这里不再处理。该错误产生HttpFailure日志,它看起来像:

enter image description here

有什么处理的最佳方式现在这个样子,一些内置的或以其他方式

+1

你能找出内部服务器错误是什么,并把它添加到您的文章? – mason

+3

ipSecurity是特定于IIS的,而ASP.NET Core则是关于通过Kestrel服务器提供Web请求的交叉平台。可能有更好的方法,但通过中间件管道可以按照http://stackoverflow.com/questions/28664686/how-do-i-get-client-ip-address-in-asp中所述检索IP地址-net-core并返回一个NotFound结果。 –

+0

@rboe啊是的,这是有道理的。所以你认为它是一个手动添加它的情况呢?正在考虑可能是这种情况 – MartinM

回答

2

达米安博德取得了blog post演示如何实现中间件处理IP白名单。

他给出了全局中间件或动作过滤器的例子。

无论哪种方式,您需要将允许的IP地址添加到您的appsettings.json,并检查客户端的IP地址。

客户端IP地址可通过HttpContext(例如context.Connection.RemoteIpAddress)获得。

如果你想加入白名单的IP地址范围,那么你可以使用NuGet包IPAddressRange,它支持多种格式,如“192.168.0.0/24”和“192.168.0.0/255.255.255.0”,包括CIDR表情和IPv6的。

这里有一个如何做,在过滤器的例子:

appsettings.json

{ 
    "IPAddressWhitelistConfiguration": { 
    "AuthorizedIPAddresses": [ 
     "::1", // IPv6 localhost 
     "127.0.0.1", // IPv4 localhost 
     "192.168.0.0/16", // Local network 
     "10.0.0.0/16", // Local network 
    ] 
    } 
} 

IPWhiteListConfiguration.cs

namespace My.Web.Configuration 
{ 
    using System.Collections.Generic; 

    public class IPWhitelistConfiguration : IIPWhitelistConfiguration 
    { 
     public IEnumerable<string> AuthorizedIPAddresses { get; set; } 
    } 
} 

Startup.cs

public class Startup 
{ 
    // ... 
    public void ConfigureServices(IServiceCollection services) 
    { 
     // ... 
     services.Configure<IPWhitelistConfiguration>(
      this.Configuration.GetSection("IPAddressWhitelistConfiguration")); 
     // ... 
    } 
} 

ClientIPAddressFilterAttribute.cs

namespace My.Web.Filters 
{ 
    using System.Collections.Generic; 
    using System.Linq; 
    using System.Net; 
    using Microsoft.AspNetCore.Mvc; 
    using Microsoft.AspNetCore.Mvc.Filters; 
    using NetTools; 
    using My.Web.Configuration; 

    public class ClientIPAddressFilterAttribute : ActionFilterAttribute 
    { 
     private readonly IEnumerable<IPAddressRange> authorizedRanges; 

     public ClientIPAddressFilterAttribute(IIPWhitelistConfiguration configuration) 
     { 
      this.authorizedRanges = configuration.AuthorizedIPAddresses 
       .Select(item => IPAddressRange.Parse(item)); 
     } 

     public override void OnActionExecuting(ActionExecutingContext context) 
     { 
      var clientIPAddress = context.HttpContext.Connection.RemoteIpAddress; 
      if (!this.authorizedRanges.Any(range => range.Contains(clientIPAddress))) 
      { 
       context.Result = new UnauthorizedResult(); 
      } 
     } 
    } 
+0

很好的答案,但我认为博客文章链接是错误的。 – CalC

+0

@CalC谢谢。现在修好! – Ergwun