vue在手机中通过本机IP地址访问webApp的方法

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了vue在手机中通过本机IP地址访问webApp的方法相关的知识,希望对你有一定的参考价值。

参考技术A vue中通过localhost:8080,就可以访问浏览项目,但是如果改成本机IP则会报错
通过localhost:8080访问效果
通过本机IP显示效果
如果想通过手机输入本机IP访问需要在package.json中配置
package.json配置
最后在手机通过IP就可以访问到webApp,或借助草料二维码生成修改后项目地址的二维码,掏出手机扫一扫即可~
通过机IP访问效果
Tips:需要手机和电脑在一个局域网(wifi)下
总结
以上所述是小编给大家介绍的vue在手机中通过本机IP地址访问webApp的方法,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对脚本之家网站的支持!
您可能感兴趣的文章:Vue2.0仿饿了么webapp单页面应用详细步骤详解Vue
webapp项目通过HBulider打包原生APPVue.js
2.0和Cordova开发webApp环境搭建方法基于VUE移动音乐WEBAPP跨域请求失败的解决方法vue-router实现webApp切换页面动画效果代码

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

【中文标题】在 ASP.NET MVC Beta 中通过 IP 地址限制对特定控制器的访问【英文标题】:Restrict access to a specific controller by IP address in ASP.NET MVC Beta 【发布时间】:2010-10-03 04:30:12 【问题描述】:

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

http://example.com/admin/AddCustomer

http://examle.com/Admin/ListCustomers

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

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

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

【问题讨论】:

一个类似的问题有你想要的答案...***.com/a/6108168/80161 【参考方案1】:

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

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

【讨论】:

热烈欢呼。我还在这里将您移植到了 ASP.NET Web API:gist.github.com/2028849。 (IIS 仅托管,因为它仍然需要 HttpContext.Current。我不确定如何从 HttpRequestMessage 获取原始客户端 IP。) 这似乎不适用于 IPv6 地址,这是一个问题,因为在许多配置中,本地主机 IP 地址返回为 ::1 @MystereMan - 如何扩展它以使用 IPv6 地址? 我已更新答案以再次工作。它对我不起作用(MVC5)。请注意,现在 AuthorizeAttribute 来自 System.Web.Http 命名空间,而不是 System.Web.Mvc 命名空间。因此,AuthorizeCore 函数已更改为 IsAuthorized。 @JoshMouch 您可以随时将其实现为Action Filter【参考方案2】:

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

【讨论】:

这是一个方便的 IP 类,可以帮助过滤:codeproject.com/KB/IP/ipnumbers.aspx @tvanfosson 受 IP 限制有多安全?我想知道的是,是否容易有人通过欺骗 IP 绕过此安全功能。 @Despertar 由于响应将被发送回发出请求的 IP 地址,如果拥有 IP 地址的机器在您的控制之下并且是安全的,那么我认为它工作得很好。与本地(不可路由)地址结合使用时,它可能更加安全。我不太可能使用它来保护对我无法控制的系统的敏感数据的访问。在这些情况下,我可能会酌情将它与用户名/密码或 API 密钥结合使用。 我应该使用 web.config 来允许或排除使用this 的 IP 地址,here 是我的问题,你知道吗? @storm 在这种情况下,网络配置可能无济于事,因为即使网络配置允许,授权属性也会限制访问。理想情况下,您只会共享公共页面。您的设置似乎有问题,它正在共享您的结帐页面的 url。您是否正确设置了 Facebook 元标记 - 特别是 og:url? developers.facebook.com/docs/sharing/best-practices【参考方案3】:

我需要一个能够处理 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);
        
    

【讨论】:

【参考方案4】:

我发现 sabbour 的解决方案非常好,但需要进行两项更改才能对我的目的更有用:

    如果允许列表为空,则允许访问。通过这种方式,您可以通过简单地更改配置(例如,用于测试部署)来允许任何 IP,或者允许除明确拒绝的 IP 之外的所有 IP。为此,我将 IPList 扩展到 包含一个 Count 属性并将其作为 CheckAllowedIPs 的一部分进行检查:

    return _allowedIpListToCheck.Count == 0 || _allowedIpListToCheck.CheckNumber(userIpAddress);
    

    重写 HandleUnauthorizedRequest 以始终​​返回 403。AuthorizeAtrribute 默认返回 401:

    public override void OnAuthorization(AuthorizationContext actionContext)
    
        if (AuthorizeCore((HttpContextBase)actionContext.HttpContext))
            return;
        HandleUnauthorizedRequest(actionContext);
    
    
    protected override void HandleUnauthorizedRequest(AuthorizationContext filterContext)
    
            filterContext.Result = new HttpStatusCodeResult(403, "IP Access Denied");
    
    

这是 FilterIpAttribute 类的完整变体:

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>
    readonly 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>
    readonly IpList _deniedIpListToCheck = new IpList();
    #endregion

    protected override bool AuthorizeCore(HttpContextBase httpContext)
    
        if (httpContext == null)
            throw new ArgumentNullException("httpContext");

        string userIpAddress = httpContext.Request.UserIp();

        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.Count == 0 || _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 actionContext)
    
        if (AuthorizeCore((HttpContextBase)actionContext.HttpContext))
            return;
        HandleUnauthorizedRequest(actionContext);
    

    protected override void HandleUnauthorizedRequest(AuthorizationContext filterContext)
    
            filterContext.Result = new HttpStatusCodeResult(403, "IP Access Denied");
    

osa 在github 上建议的获取用户 IP 的扩展方法

public static class HttpUtils 

    public static string UserIp(this HttpRequestBase request)
    
        var ip = request["HTTP_X_FORWARDED_FOR"];

        if (!string.IsNullOrWhiteSpace(ip))
        
            ip = ip.Split(',').Last().Trim();
        

        if (string.IsNullOrWhiteSpace(ip))
        
            ip = request.UserHostAddress;
        

        return ip;
    

最后是IPList修改(完整来源是here):

internal class IpArrayList

    //[...]
    public int Count
    
        get  return _ipNumList.Count; 
    

 

public class IpList

      //[...]
     public int Count
     
         get  return _usedList.Count; 
     

【讨论】:

【参考方案5】:

我使用的最简单的方法

第一:

在配置表(如果有)或任何其他表上添加一行,并将可访问的 IP 插入此表。

秒:

将此操作过滤器添加到您的 startup.cs

public class IpAuthAttribute : ActionFilterAttribute

    public override void OnActionExecuting(ActionExecutingContext filterContext)
    
        base.OnActionExecuting(filterContext);
        string ip = System.Web.HttpContext.Current.Request.UserHostAddress;
        string ips = "";
        using (var db = new DataBase())
        
            ips = db.Configs.SingleOrDefault().IP;
        
        if (!ips.Contains(ip))
        
            filterContext.Result = new RedirectToRouteResult(new System.Web.Routing.RouteValueDictionary(new
            
                controller = "Account",
                action = "OutOfRange"
            ));
        
    

然后在您想要在控制器上执行的每个操作上使用它

[IpAuth]
public ActionResult Index()

    return View();

【讨论】:

以上是关于vue在手机中通过本机IP地址访问webApp的方法的主要内容,如果未能解决你的问题,请参考以下文章

使用套接字在eclipse android程序中通过IP地址发送消息

无法将 IP 地址“xxx”的 RSA 主机密钥添加到已知主机列表 (/home/webapp/.ssh/known_hosts)

使用真实手机测试开发中的项目

Android模拟器如何加载本机地址及访问本机服务器

Vue入门实践 每日一文Webapp

在 C# 中通过远程处理获取外部 IP 地址