当前位置:  开发笔记 > 编程语言 > 正文

在ASP.NET MVC Beta中通过IP地址限制对特定控制器的访问

如何解决《在ASP.NETMVCBeta中通过IP地址限制对特定控制器的访问》经验,为你挑选了2个好方法。

我有一个包含AdminController类的ASP.NET MVC项目,并给我这样的URls:

http://example.com/admin/AddCustomer

http://examle.com/Admin/ListCustomers

我想配置服务器/应用程序,以便只能从192.168.0.0/24网络(即我们的LAN)访问包含/ Admin的 URI

我想将此控制器限制为只能从某些IP地址访问.

在WebForms下,/ admin /是一个物理文件夹,我可以在IIS中限制...但是使用MVC,当然,没有物理文件夹.这是使用web.config或属性实现的,还是我需要拦截HTTP请求来实现这一目标?



1> sabbour..:

我知道这是一个老问题,但我今天需要有这个功能,所以我实现了它并考虑在这里发布它.

使用此处的IPList类(http://www.codeproject.com/KB/IP/ipnumbers.aspx)

过滤器属性FilterIPAttribute.cs:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Http;
using System.Security.Principal;
using System.Configuration;

namespace Miscellaneous.Attributes.Controller
{

    /// 
    /// Filter by IP address
    /// 
    public class FilterIPAttribute : AuthorizeAttribute
    {

        #region Allowed
        /// 
        /// Comma seperated string of allowable IPs. Example "10.2.5.41,192.168.0.22"
        /// 
        /// 
        public string AllowedSingleIPs { get; set; }

        /// 
        /// Comma seperated string of allowable IPs with masks. Example "10.2.0.0;255.255.0.0,10.3.0.0;255.255.0.0"
        /// 
        /// The masked I ps.
        public string AllowedMaskedIPs { get; set; }

        /// 
        /// Gets or sets the configuration key for allowed single IPs
        /// 
        /// The configuration key single I ps.
        public string ConfigurationKeyAllowedSingleIPs { get; set; }

        /// 
        /// Gets or sets the configuration key allowed mmasked IPs
        /// 
        /// The configuration key masked I ps.
        public string ConfigurationKeyAllowedMaskedIPs { get; set; }

        /// 
        /// List of allowed IPs
        /// 
        IPList allowedIPListToCheck = new IPList();
        #endregion

        #region Denied
        /// 
        /// Comma seperated string of denied IPs. Example "10.2.5.41,192.168.0.22"
        /// 
        /// 
        public string DeniedSingleIPs { get; set; }

        /// 
        /// Comma seperated string of denied IPs with masks. Example "10.2.0.0;255.255.0.0,10.3.0.0;255.255.0.0"
        /// 
        /// The masked I ps.
        public string DeniedMaskedIPs { get; set; }


        /// 
        /// Gets or sets the configuration key for denied single IPs
        /// 
        /// The configuration key single I ps.
        public string ConfigurationKeyDeniedSingleIPs { get; set; }

        /// 
        /// Gets or sets the configuration key for denied masked IPs
        /// 
        /// The configuration key masked I ps.
        public string ConfigurationKeyDeniedMaskedIPs { get; set; }

        /// 
        /// List of denied IPs
        /// 
        IPList deniedIPListToCheck = new IPList();
        #endregion


        /// 
        /// Determines whether access to the core framework is authorized.
        /// 
        /// The HTTP context, which encapsulates all HTTP-specific information about an individual HTTP request.
        /// 
        /// true if access is authorized; otherwise, false.
        /// 
        /// The  parameter is null.
        protected override bool IsAuthorized(HttpActionContext actionContext)
        {
            if (actionContext == null)
                throw new ArgumentNullException("actionContext");

            string userIpAddress = ((HttpContextWrapper)actionContext.Request.Properties["MS_HttpContext"]).Request.UserHostName;

            try
            {
                // Check that the IP is allowed to access
                bool ipAllowed = CheckAllowedIPs(userIpAddress);

                // Check that the IP is not denied to access
                bool ipDenied = CheckDeniedIPs(userIpAddress);    

                // Only allowed if allowed and not denied
                bool finallyAllowed = ipAllowed && !ipDenied;

                return finallyAllowed;
            }
            catch (Exception e)
            {
                // Log the exception, probably something wrong with the configuration
            }

            return true; // if there was an exception, then we return true
        }

        /// 
        /// Checks the allowed IPs.
        /// 
        /// The user ip address.
        /// 
        private bool CheckAllowedIPs(string userIpAddress)
        {
            // Populate the IPList with the Single IPs
            if (!string.IsNullOrEmpty(AllowedSingleIPs))
            {
                SplitAndAddSingleIPs(AllowedSingleIPs, allowedIPListToCheck);
            }

            // Populate the IPList with the Masked IPs
            if (!string.IsNullOrEmpty(AllowedMaskedIPs))
            {
                SplitAndAddMaskedIPs(AllowedMaskedIPs, allowedIPListToCheck);
            }

            // Check if there are more settings from the configuration (Web.config)
            if (!string.IsNullOrEmpty(ConfigurationKeyAllowedSingleIPs))
            {
                string configurationAllowedAdminSingleIPs = ConfigurationManager.AppSettings[ConfigurationKeyAllowedSingleIPs];
                if (!string.IsNullOrEmpty(configurationAllowedAdminSingleIPs))
                {
                    SplitAndAddSingleIPs(configurationAllowedAdminSingleIPs, allowedIPListToCheck);
                }
            }

            if (!string.IsNullOrEmpty(ConfigurationKeyAllowedMaskedIPs))
            {
                string configurationAllowedAdminMaskedIPs = ConfigurationManager.AppSettings[ConfigurationKeyAllowedMaskedIPs];
                if (!string.IsNullOrEmpty(configurationAllowedAdminMaskedIPs))
                {
                    SplitAndAddMaskedIPs(configurationAllowedAdminMaskedIPs, allowedIPListToCheck);
                }
            }

            return allowedIPListToCheck.CheckNumber(userIpAddress);
        }

        /// 
        /// Checks the denied IPs.
        /// 
        /// The user ip address.
        /// 
        private bool CheckDeniedIPs(string userIpAddress)
        {
            // Populate the IPList with the Single IPs
            if (!string.IsNullOrEmpty(DeniedSingleIPs))
            {
                SplitAndAddSingleIPs(DeniedSingleIPs, deniedIPListToCheck);
            }

            // Populate the IPList with the Masked IPs
            if (!string.IsNullOrEmpty(DeniedMaskedIPs))
            {
                SplitAndAddMaskedIPs(DeniedMaskedIPs, deniedIPListToCheck);
            }

            // Check if there are more settings from the configuration (Web.config)
            if (!string.IsNullOrEmpty(ConfigurationKeyDeniedSingleIPs))
            {
                string configurationDeniedAdminSingleIPs = ConfigurationManager.AppSettings[ConfigurationKeyDeniedSingleIPs];
                if (!string.IsNullOrEmpty(configurationDeniedAdminSingleIPs))
                {
                    SplitAndAddSingleIPs(configurationDeniedAdminSingleIPs, deniedIPListToCheck);
                }
            }

            if (!string.IsNullOrEmpty(ConfigurationKeyDeniedMaskedIPs))
            {
                string configurationDeniedAdminMaskedIPs = ConfigurationManager.AppSettings[ConfigurationKeyDeniedMaskedIPs];
                if (!string.IsNullOrEmpty(configurationDeniedAdminMaskedIPs))
                {
                    SplitAndAddMaskedIPs(configurationDeniedAdminMaskedIPs, deniedIPListToCheck);
                }
            }

            return deniedIPListToCheck.CheckNumber(userIpAddress);
        }

        /// 
        /// Splits the incoming ip string of the format "IP,IP" example "10.2.0.0,10.3.0.0" and adds the result to the IPList
        /// 
        /// The ips.
        /// The list.
        private void SplitAndAddSingleIPs(string ips,IPList list)
        {
            var splitSingleIPs = ips.Split(',');
            foreach (string ip in splitSingleIPs)
                list.Add(ip);
        }

        /// 
        /// Splits the incoming ip string of the format "IP;MASK,IP;MASK" example "10.2.0.0;255.255.0.0,10.3.0.0;255.255.0.0" and adds the result to the IPList
        /// 
        /// The ips.
        /// The list.
        private void SplitAndAddMaskedIPs(string ips, IPList list)
        {
            var splitMaskedIPs = ips.Split(',');
            foreach (string maskedIp in splitMaskedIPs)
            {
                var ipAndMask = maskedIp.Split(';');
                list.Add(ipAndMask[0], ipAndMask[1]); // IP;MASK
            }
        }

        public override void OnAuthorization(AuthorizationContext filterContext)
        {
            base.OnAuthorization(filterContext);
        }
    }
}

用法示例:

1.直接在代码中指定IP

    [FilterIP(
         AllowedSingleIPs="10.2.5.55,192.168.2.2",
         AllowedMaskedIPs="10.2.0.0;255.255.0.0,192.168.2.0;255.255.255.0"
    )]
    public class HomeController {
      // Some code here
    }

2.或者,从Web.config加载配置

    [FilterIP(
         ConfigurationKeyAllowedSingleIPs="AllowedAdminSingleIPs",
         ConfigurationKeyAllowedMaskedIPs="AllowedAdminMaskedIPs",
         ConfigurationKeyDeniedSingleIPs="DeniedAdminSingleIPs",
         ConfigurationKeyDeniedMaskedIPs="DeniedAdminMaskedIPs"
    )]
    public class HomeController {
      // Some code here
    }




     
     
        
        



璀璨的欢呼声.我还在此处移植到了ASP.NET Web API:https://gist.github.com/2028849.(IIS仅托管,因为它仍然需要HttpContext.Current.我不知道如何从HttpRequestMessage获取原始客户端IP.)
我已经更新了答案再次工作.它对我不起作用(MVC5).请注意,AuthorizeAttribute现在来自System.Web.Http命名空间,而不是System.Web.Mvc命名空间.因此,AuthorizeCore函数已更改为IsAuthorized.

2> tvanfosson..:

您应该有权访问UserHostAddress控制器中的Request对象来进行限制.我建议您可以扩展AuthorizeAttribute并添加IP地址限制,以便您可以简单地装饰需要此保护的任何方法或控制器.

推荐阅读
乐韵答题
这个屌丝很懒,什么也没留下!
DevBox开发工具箱 | 专业的在线开发工具网站    京公网安备 11010802040832号  |  京ICP备19059560号-6
Copyright © 1998 - 2020 DevBox.CN. All Rights Reserved devBox.cn 开发工具箱 版权所有