首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >在ASP.NET MVC Beta中通过IP地址限制对特定控制器的访问

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

Stack Overflow用户
提问于 2009-01-23 17:01:37
回答 5查看 64.2K关注 0票数 71

我有一个包含AdminController类的ASP.NET MVC项目,并给出了如下的URls:

http://example.com/admin/AddCustomer

http://examle.com/Admin/ListCustomers

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

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

在WebForms下,/admin/是一个物理文件夹,我可以在IIS...但在MVC中,当然没有物理文件夹。这可以使用web.config或属性来实现吗?或者我需要截获HTTP请求才能实现这一点吗?

EN

回答 5

Stack Overflow用户

回答已采纳

发布于 2011-01-05 22:22:22

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

在这里使用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
{

    /// <summary>
    /// Filter by IP address
    /// </summary>
    public class FilterIPAttribute : AuthorizeAttribute
    {

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

        /// <summary>
        /// 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"
        /// </summary>
        /// <value>The masked I ps.</value>
        public string AllowedMaskedIPs { get; set; }

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

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

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

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

        /// <summary>
        /// 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"
        /// </summary>
        /// <value>The masked I ps.</value>
        public string DeniedMaskedIPs { get; set; }


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

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

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


        /// <summary>
        /// Determines whether access to the core framework is authorized.
        /// </summary>
        /// <param name="actionContext">The HTTP context, which encapsulates all HTTP-specific information about an individual HTTP request.</param>
        /// <returns>
        /// true if access is authorized; otherwise, false.
        /// </returns>
        /// <exception cref="T:System.ArgumentNullException">The <paramref name="httpContext"/> parameter is null.</exception>
        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
        }

        /// <summary>
        /// Checks the allowed IPs.
        /// </summary>
        /// <param name="userIpAddress">The user ip address.</param>
        /// <returns></returns>
        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);
        }

        /// <summary>
        /// Checks the denied IPs.
        /// </summary>
        /// <param name="userIpAddress">The user ip address.</param>
        /// <returns></returns>
        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);
        }

        /// <summary>
        /// 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
        /// </summary>
        /// <param name="ips">The ips.</param>
        /// <param name="list">The list.</param>
        private void SplitAndAddSingleIPs(string ips,IPList list)
        {
            var splitSingleIPs = ips.Split(',');
            foreach (string ip in splitSingleIPs)
                list.Add(ip);
        }

        /// <summary>
        /// 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
        /// </summary>
        /// <param name="ips">The ips.</param>
        /// <param name="list">The list.</param>
        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
    }


<configuration>
<appSettings>
    <add key="AllowedAdminSingleIPs" value="localhost,127.0.0.1"/> <!-- Example "10.2.80.21,192.168.2.2" -->
    <add key="AllowedAdminMaskedIPs" value="10.2.0.0;255.255.0.0"/> <!-- Example "10.2.0.0;255.255.0.0,192.168.2.0;255.255.255.0" -->
    <add key="DeniedAdminSingleIPs" value=""/>    <!-- Example "10.2.80.21,192.168.2.2" -->
    <add key="DeniedAdminMaskedIPs" value=""/>    <!-- Example "10.2.0.0;255.255.0.0,192.168.2.0;255.255.255.0" -->
</appSettings>
</configuration>
票数 111
EN

Stack Overflow用户

发布于 2009-01-23 17:05:17

您应该有权访问要对其执行限制的控制器中的请求对象中的UserHostAddress。我建议您可以扩展AuthorizeAttribute并在其上添加IP地址限制,这样您就可以简单地修饰需要这种保护的任何方法或控制器。

票数 9
EN

Stack Overflow用户

发布于 2016-08-21 02:49:18

我需要一个可以处理IPv6和IP范围的MVC4解决方案来解决这个问题。此外,我需要使用白名单和黑名单进行授权,但当IP既不是白名单也不是黑名单时,还需要使用常规授权过程。

这是我从@sabbour和@Richard Szalay(How to check a input IP fall in a specific IP range)很棒的帖子中得到的解决方案,所以我把它贴回这里,无论对谁有帮助。

public class MagniAuthorizeAttribute : FilterAttribute, IAuthorizationFilter
{

    #region Allowed

    public bool IsPublic { get; set; }
    /// <summary>
    /// Comma seperated string of allowable IPs. Example "10.2.5.41,192.168.0.22"
    /// </summary>
    /// <value></value>        
    public string AllowedSingleIPs { get; set; }

    /// <summary>
    /// 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"
    /// </summary>
    /// <value>The masked I ps.</value>
    public string AllowedIPRanges { get; set; }

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

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

    #endregion

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

    /// <summary>
    /// 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"
    /// </summary>
    /// <value>The masked I ps.</value>
    public string DeniedIPRanges { get; set; }


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

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

    #endregion


    /// <summary>
    /// Checks the allowed IPs.
    /// </summary>
    /// <param name="userIpAddress">The user ip address.</param>
    /// <returns></returns>
    private bool CheckAllowedIPs(IPAddress userIpAddress)
    {
        List<IPAddress> allowedIPsToCheck = new List<IPAddress>();
        List<IPAddressRange> allowedIPRangesToCheck = new List<IPAddressRange>();

        // Populate the IPList with the Single IPs
        if (!string.IsNullOrEmpty(AllowedSingleIPs))
        {
            SplitAndAddSingleIPs(AllowedSingleIPs, allowedIPsToCheck);
        }

        // Populate the IPList with the Masked IPs
        if (!string.IsNullOrEmpty(AllowedIPRanges))
        {
            SplitAndAddIPRanges(AllowedIPRanges, allowedIPRangesToCheck);
        }

        // 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, allowedIPsToCheck);
            }
        }

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

        return allowedIPsToCheck.Any(a => a.Equals(userIpAddress)) || allowedIPRangesToCheck.Any(a => a.IsInRange(userIpAddress));
    }

    /// <summary>
    /// Checks the denied IPs.
    /// </summary>
    /// <param name="userIpAddress">The user ip address.</param>
    /// <returns></returns>
    private bool CheckDeniedIPs(IPAddress userIpAddress)
    {
        List<IPAddress> deniedIPsToCheck = new List<IPAddress>();
        List<IPAddressRange> deniedIPRangesToCheck = new List<IPAddressRange>();

        // Populate the IPList with the Single IPs
        if (!string.IsNullOrEmpty(DeniedSingleIPs))
        {
            SplitAndAddSingleIPs(DeniedSingleIPs, deniedIPsToCheck);
        }

        // Populate the IPList with the Masked IPs
        if (!string.IsNullOrEmpty(DeniedIPRanges))
        {
            SplitAndAddIPRanges(DeniedIPRanges, deniedIPRangesToCheck);
        }

        // 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, deniedIPsToCheck);
            }
        }

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

        return deniedIPsToCheck.Any(a => a.Equals(userIpAddress)) || deniedIPRangesToCheck.Any(a => a.IsInRange(userIpAddress));
    }

    /// <summary>
    /// 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 IPAddress list
    /// </summary>
    /// <param name="ips">The ips.</param>
    /// <param name="list">The list.</param>
    private void SplitAndAddSingleIPs(string ips, List<IPAddress> list)
    {
        var splitSingleIPs = ips.Split(',');
        IPAddress ip;

        foreach (string ipString in splitSingleIPs)
        {
            if(IPAddress.TryParse(ipString, out ip))
                list.Add(ip);
        }
    }

    /// <summary>
    /// Splits the incoming ip ranges string of the format "IP-IP,IP-IP" example "10.2.0.0-10.2.255.255,10.3.0.0-10.3.255.255" and adds the result to the IPAddressRange list
    /// </summary>
    /// <param name="ips">The ips.</param>
    /// <param name="list">The list.</param>
    private void SplitAndAddIPRanges(string ips, List<IPAddressRange> list)
    {
        var splitMaskedIPs = ips.Split(',');
        IPAddress lowerIp;
        IPAddress upperIp;
        foreach (string maskedIp in splitMaskedIPs)
        {
            var ipRange = maskedIp.Split('-');
            if (IPAddress.TryParse(ipRange[0], out lowerIp) && IPAddress.TryParse(ipRange[1], out upperIp))
                list.Add(new IPAddressRange(lowerIp, upperIp));
        }
    }

    protected void HandleUnauthorizedRequest(AuthorizationContext context)
    {
        context.Result = new RedirectToRouteResult(new RouteValueDictionary { { "Controller", "Home" },
                                                                                    { "Action", "Login" },
                                                                                    { "OriginalURL", context.HttpContext.Request.Url.AbsoluteUri } });
    }

    protected bool AuthorizeCore(AuthorizationContext context)
    {
        try
        {
            string userIPString = context.HttpContext.Request.UserHostName;
            IPAddress userIPAddress = IPAddress.Parse(userIPString);

            // Check that the IP is allowed to access
            bool? ipAllowed = CheckAllowedIPs(userIPAddress) ? true : (bool?)null;

            // Check that the IP is not denied to access
            ipAllowed = CheckDeniedIPs(userIPAddress) ? false : ipAllowed;

            if (ipAllowed.HasValue)
            {
                return ipAllowed.Value;
            }

            var serverSession = context.HttpContext.Session;

            UserSession session = null;

            //usersession in server session
            if (serverSession[Settings.HttpContextUserSession] != null)
            {
                session = (UserSession)serverSession[Settings.HttpContextUserSession];
                Trace.TraceInformation($"[{MethodBase.GetCurrentMethod().Name}] UserId:" + session.UserId + ". ClientId: " + session.ClientId);
                return true;
            }

            //usersession in database from cookie
            session = UserSession.GetSession(context.HttpContext.Request.Cookies.Get("sessionId").Value);
            if (session != null)
            {
                Trace.TraceInformation($"[{MethodBase.GetCurrentMethod().Name}] Session found for cookie {context.HttpContext.Request.Cookies.Get("sessionId").Value}");
                serverSession[Settings.HttpContextUserSession] = session;
                Trace.TraceInformation($"[{MethodBase.GetCurrentMethod().Name}] UserId:" + session.UserId + ". ClientId: " + session.ClientId);

                return true;
            }
            else
            {
                Trace.TraceInformation($"[{MethodBase.GetCurrentMethod().Name}] No session found for cookie {serverSession["cookie"]}");
                return false;
            }

        }
        catch (Exception ex)
        {
            Trace.TraceError($"[{MethodBase.GetCurrentMethod().Name}] exception: {ex.Message} - trace {ex.StackTrace}");
            return false;
        }
    }

    public void OnAuthorization(AuthorizationContext actionContext)
    {
        if (IsPublic == false && AuthorizeCore(actionContext) == false)
        {
            HandleUnauthorizedRequest(actionContext);
        }
    }
}
票数 3
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/473687

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档