码迷,mamicode.com
首页 > Web开发 > 详细

Web应用限制IP访问功能的实现

时间:2015-10-10 16:48:53      阅读:314      评论:0      收藏:0      [点我收藏+]

标签:

如果你的web应用受到恶意扫描或攻击,你会怎么处理呢?大多数时候从应用日志里可以看到恶意扫描或攻击,遇到此类情况,如有一个可以进行IP访问控制的功能就好些了。

现将在MVC下实现的一个IP访问限制功能分享一下:

1、通过路由规则配置来设置禁止IP访问

    public class RouteConfig
    {
        public static void RegisterRoutes(RouteCollection routes)
        {
            routes.IgnoreRoute("{resource}.axd/{*pathInfo}");

            //通过路由规则配置来设置禁止IP访问
            routes.MapRoute(
                name: "Abandon",
                url: "{controller}/{action}/{id}",
                defaults: new { controller = "Account", action = "AbandonIP", id = UrlParameter.Optional },
                constraints: new { customConstraint = new AbandonIPConstraint() }//自定义限制路由
            );

            routes.MapRoute(
                name: "Default",
                url: "{controller}/{action}/{id}",
                defaults: new { controller = "Account", action = "Index", id = UrlParameter.Optional }
            );

            //GlobalHost.Configuration.ConnectionTimeout = TimeSpan.FromSeconds(50);
          
        }
    }

 2、自定义限制路由的实现

    public class AbandonIPConstraint : IRouteConstraint
    {
        public bool Match(HttpContextBase httpContext, Route route, string parameterName,
         RouteValueDictionary values, RouteDirection routeDirection)
        {
            var currentIp = httpContext.Request.UserHostAddress;
            //如果当前访问用户的ip是127.0.0.1,则匹配Abandon路由,如果不是则匹配其他路由
            // return currentIp == "110.19.222.144";
            bool result = SecurityHelper.CheckIPAddress(currentIp);
            return result;
        }
    }

 3、IP检查功能

        /// <summary>
        /// 检查用户IP地址是否被限制登录系统
        /// </summary>
        /// <param name="ipAddress">IP地址</param>
        /// <returns>是否符合限制</returns>
        public static bool CheckIPAddress(string ipAddress)
        {
            bool result = false;
            var list = GetCacheAbandonIpAddressList();
            if (list != null && list.Count > 0)
            {
                foreach (AbandonIpaddressEntity model in list)
                {
                    //删除的或者没有启用的排除掉
                    if (model.DeletionStateCode == 1 || model.Enabled==0)
                    {
                        continue;
                    }
                    string ipAddressType = model.IpAddressType;
                    string ipAddressContent = model.IpAddressContent;
                    if (string.Equals(ipAddressType, "Single",StringComparison.OrdinalIgnoreCase))
                    {
                        // 匹配单个IP
                        result = CheckSingleIPAddress(ipAddress, ipAddressContent);
                    }
                    else if (string.Equals(ipAddressType, "Range", StringComparison.OrdinalIgnoreCase))
                    {
                        // 匹配ip地址段
                        result = CheckIPAddressWithRange(ipAddress, ipAddressContent);
                    }
                    else if (string.Equals(ipAddressType, "Mask", StringComparison.OrdinalIgnoreCase))
                    {
                        // 匹配带掩码的地址段
                        result = CheckIPAddressWithMask(ipAddress, ipAddressContent);
                    }
                    if (result)
                    {
                        break;
                    }
                }
            }
            return result;
        }
        /// <summary>
        /// 检查是否匹配单个IP
        /// </summary>
        /// <param name="ipAddress"></param>
        /// <param name="sourceIp"></param>
        /// <returns></returns>
        public static bool CheckSingleIPAddress(string ipAddress, string sourceIp)
        {
            return ipAddress.Equals(sourceIp);
        }

        /// <summary>
        /// 检查是否匹配地址段
        /// </summary>
        /// <param name="ipAddress">192.168.0.8</param>
        /// <param name="ipRange">192.168.0.1-192.168.0.10</param>
        /// <returns></returns>
        public static bool CheckIPAddressWithRange(string ipAddress, string ipRange)
        {
            //先判断符合192.168.0.1-192.168.0.10 的正则表达式
            //在判断ipAddress是否有效
            string startIp = ipRange.Split(-)[0];
            string endIp = ipRange.Split(-)[1];
            //如果大于等于 startip 或者 小于等于endip
            if (CompareIp(ipAddress, startIp) == 2 && CompareIp(ipAddress, endIp) == 0 || CompareIp(ipAddress, startIp) == 1 || CompareIp(ipAddress, endIp) == 1)
            {
                return true;
            }
            return false;
        }

        /// <summary>
        /// 比较两个IP地址,比较前可以先判断是否是IP地址
        /// </summary>
        /// <param name="ip1"></param>
        /// <param name="ip2"></param>
        /// <returns>1:相等;  0:ip1小于ip2 ; 2:ip1大于ip2;-1 不符合ip正则表达式 </returns>
        public static int CompareIp(string ip1, string ip2)
        {
            String[] arr1 = ip1.Split(.);
            String[] arr2 = ip2.Split(.);
            for (int i = 0; i < arr1.Length; i++)
            {
                int a1 = int.Parse(arr1[i]);
                int a2 = int.Parse(arr2[i]);
                if (a1 > a2)
                {
                    return 2;
                }
                else if (a1 < a2)
                {
                    return 0;
                }
            }
            return 1;
        }

        /// <summary>
        /// 检查是否匹配带通配符的IP地址
        /// </summary>
        /// <param name="ipAddress">192.168.1.1</param>
        /// <param name="ipWithMask">192.168.1.*</param>
        /// <returns></returns>
        public static bool CheckIPAddressWithMask(string ipAddress, string ipWithMask)
        {
            //先判断是否符合192.168.1.*
            //然后判断
            string[] arr1 = ipAddress.Split(.);
            string[] arr2 = ipWithMask.Split(.);
            for (int i = 0; i < arr1.Length; i++)
            {
                if (!(arr2[i].Equals("*") || arr1[i].Equals(arr2[i])))
                {
                    return false;
                }
            }
            return true;
        }

4、限制的IP做了缓存,缓存的实现大家可以自己按照具体环境去实现

        /// <summary>
        /// 移除IP缓存数据
        /// </summary>
        public static void RemoveCacheAbandonIpAddressList()
        {
            //移除
            DataCacheHelper.RemoveCache("GetCacheAbandonIpAddressList");
        }
        /// <summary>
        /// 获取缓存的数据
        /// </summary>
        /// <returns></returns>
        public static List<AbandonIpaddressEntity> GetCacheAbandonIpAddressList()
        {
            string cacheKey = "GetCacheAbandonIpAddressList";
            if (null == DataCacheHelper.GetCache(cacheKey))
            {
                lock (Locker)
                {
                    if (null == DataCacheHelper.GetCache(cacheKey))
                    {
                        try
                        {
                            IDbHelper dbHelper = DbHelperFactory.GetHelper(BaseSystemInfo.UserCenterDbType, BaseSystemInfo.UserCenterDbConnection);
                            AbandonIpaddressManager manager = new AbandonIpaddressManager(dbHelper);
                            List<KeyValuePair<string, object>> parameters = new List<KeyValuePair<string, object>>();
                            var list = manager.GetList<AbandonIpaddressEntity>(parameters);
                            DataCacheHelper.SetCache(cacheKey, list, null, DateTime.Now.AddMinutes(120), Cache.NoSlidingExpiration, CacheItemPriority.NotRemovable, null);
                            return list;
                        }
                        catch (Exception ex)
                        {
                            LogHelper.WriteErrorLog("private List<AbandonIpaddressEntity> GetCacheAbandonIpAddressList()", ex);
                            return null;
                        }
                    }
                }
            }
            return DataCacheHelper.GetCache(cacheKey) as List<AbandonIpaddressEntity>;
        }

5、受限IP维护功能

    /// <summary>
    /// AbandonController
    /// 
    /// 禁止登录系统的控制器
    /// 
    /// 修改纪录
    /// 
    /// 2015-10-10 版本:1.0 SongBiao 创建文件。   /// 
    /// <author>
    ///     <name>SongBiao</name>
    ///     <date>2015-10-10</date>
    /// </author>
    /// </summary>

    public class AbandonController : BaseController
    {
        //
        // GET: /Abandon/
        [AjaxRequest]
        [CustomAuthorizeAttribute]
        public ActionResult Index()
        {
            return View();
        }

        [AjaxRequest]
        [CustomAuthorizeAttribute]
        public ActionResult ListIPAddress(Pager pager, string sort, string direction)
        {
            Hashtable result = new Hashtable();
            DataTable dt = new DataTable();
            List<KeyValuePair<string, object>> dbParameters = new List<KeyValuePair<string, object>>();
            List<string> listWhere = new List<string>();
            string conditions = string.Empty;
            string tableName = AbandonIpaddressEntity.TableName;
            string selectField = " * ";
            int totalRows = 0;
            string orderBy = sort + " " + direction;
            try
            {
                IDbHelper dbHelper = DbHelperFactory.GetHelper(BaseSystemInfo.UserCenterDbType, BaseSystemInfo.UserCenterDbConnection);
                dt = DbLogic.GetDataTableByPage(dbHelper, out totalRows, tableName, selectField, pager.pageNo, pager.pageSize, conditions, dbHelper.MakeParameters(dbParameters), orderBy);
                pager.totalPages = totalRows;
                result.Add("status", "true");
                result.Add("message", "成功获取数据。");
                result.Add("pager.pageNo", pager.pageNo);
                result.Add("rows", dt);//DataTableHelper.DataTable2Json(dt)
                result.Add("pager.totalRows", pager.totalPages);
                result.Add("sort", sort);
                result.Add("direction", direction);
            }
            catch (Exception ex)
            {
                result.Add("status", "false");
                result.Add("message", "系统异常:" + ex.Message);
                result.Add("pager.pageNo", pager.pageNo);
                result.Add("rows", dt);//DataTableHelper.DataTable2Json(dt)
                result.Add("pager.totalRows", pager.totalPages);
                result.Add("sort", sort);
                result.Add("direction", direction);
                LogHelper.OracleWarn(OperateContext.Current.UserInfo, "获取限制IP数据出现异常", ex.Message, "ListIPAddress", typeof(AbandonController), ex);
            }
            result.Add("span", (DateTime.Now - begin).TotalMilliseconds);
            return Json(result, JsonRequestBehavior.AllowGet);
        }

        /// <summary>
        /// IP地址是否限制
        /// </summary>
        /// <param name="ipAddress"></param>
        /// <returns></returns>
        public ActionResult CheckIPAddress(string ipAddress)
        {
            if (SecurityHelper.CheckIPAddress(ipAddress))
            {
                return Content(ipAddress + "不允许登录系统");
            }
            else
            {
                return Content(ipAddress + "可以登录系统");
            }
        }

        /// <summary>
        /// 添加受限的IP地址
        /// </summary>
        /// <returns></returns>
        public ActionResult AddIP()
        {
            return View();
        }

        /// <summary>
        /// 显示受限IP地址
        /// </summary>
        /// <returns></returns>
        public ActionResult ShowIP(string id)
        {
            IDbHelper dbHelper = DbHelperFactory.GetHelper(BaseSystemInfo.UserCenterDbType, BaseSystemInfo.UserCenterDbConnection);
            AbandonIpaddressManager manager = new AbandonIpaddressManager(dbHelper, OperateContext.Current.UserInfo);
            AbandonIpaddressEntity entity = manager.GetObject(id);
            //ViewBag.AbandonIpaddressEntity = entity;
            return View(entity);
        }

        /// <summary>
        /// 显示受限IP地址
        /// </summary>
        /// <returns></returns>
        public ActionResult EditIP(string id)
        {
            IDbHelper dbHelper = DbHelperFactory.GetHelper(BaseSystemInfo.UserCenterDbType, BaseSystemInfo.UserCenterDbConnection);
            AbandonIpaddressManager manager = new AbandonIpaddressManager(dbHelper, OperateContext.Current.UserInfo);
            AbandonIpaddressEntity entity = manager.GetObject(id);
            //ViewBag.AbandonIpaddressEntity = entity;
            return View(entity);
        }

        /// <summary>
        /// 添加受限的IP
        /// </summary>
        /// <param name="abandonIpaddress"></param>
        /// <returns></returns>
        [HttpPost]
        public ActionResult SaveIP(AbandonIpaddressEntity abandonIpaddress)
        {
            //Hashtable result = new Hashtable();
            BaseResult baseResult = new BaseResult();
            baseResult.Status = false;
            AbandonIpaddressEntity entity = new AbandonIpaddressEntity();
            if (string.IsNullOrWhiteSpace(abandonIpaddress.Id))
            {
                entity.Id = Guid.NewGuid().ToString();
                entity.DeletionStateCode = 0;
                entity.Enabled = 1;
            }
            entity.IpAddressType = abandonIpaddress.IpAddressType;
            entity.IpAddressContent = abandonIpaddress.IpAddressContent;
            IDbHelper dbHelper = DbHelperFactory.GetHelper(BaseSystemInfo.UserCenterDbType, BaseSystemInfo.UserCenterDbConnection);
            AbandonIpaddressManager manager = new AbandonIpaddressManager(dbHelper, OperateContext.Current.UserInfo);
            //判断IP是否已受限
            var list = SecurityHelper.GetCacheAbandonIpAddressList();
            bool hasIP = false;
            AbandonIpaddressEntity hasModel = null;
            if (list != null && list.Count > 0)
            {
                foreach (AbandonIpaddressEntity model in list)
                {
                    string ipAddressType = model.IpAddressType;
                    string ipAddressContent = model.IpAddressContent;//IP检查是否存在
                    if (string.Equals(ipAddressContent, abandonIpaddress.IpAddressContent, StringComparison.OrdinalIgnoreCase))
                    {
                        hasIP = true;
                        hasModel = model;
                        break;
                    }
                }
            }
            if (hasIP)
            {
                //已存在受限的IP 不允许再添加了  更新一下状态即可
                if (string.IsNullOrWhiteSpace(abandonIpaddress.Id))
                {
                    hasModel.DeletionStateCode = 0;
                    hasModel.Enabled = 1;
                }
                else
                {
                    hasModel.DeletionStateCode = abandonIpaddress.DeletionStateCode;
                    hasModel.Enabled = abandonIpaddress.Enabled;
                }
                manager.Update(hasModel);
                baseResult.Status = true;
                baseResult.StatusMessage = "IP已受限,不允许重复添加!";
            }
            else
            {
                if (string.IsNullOrWhiteSpace(abandonIpaddress.Id))
                {
                    string result = manager.Add(entity, false, true);
                    if (!string.IsNullOrWhiteSpace(result))
                    {
                        baseResult.Status = true;
                        baseResult.StatusMessage = "添加成功。";
                    }
                    else
                    {
                        baseResult.StatusMessage = "添加失败了。";
                    }
                }
                else
                {
                    //状态更新 IP类型和值 是不允许修改的
                    entity.Id = abandonIpaddress.Id;
                    entity.DeletionStateCode = abandonIpaddress.DeletionStateCode;
                    entity.Enabled = abandonIpaddress.Enabled;
                    manager.Update(entity);
                    baseResult.Status = true;
                    baseResult.StatusMessage = "更新成功。";
                }
            }
            //操作成功 清除一下缓存
            if (baseResult.Status)
            {
                SecurityHelper.RemoveCacheAbandonIpAddressList();
            }
            return Json(baseResult, JsonRequestBehavior.AllowGet);
        }


        /// <summary>
        /// 删除受限的IP
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public ActionResult DeleteIP(string id)
        {
            BaseResult baseResult = new BaseResult();
            baseResult.Status = false;
            IDbHelper dbHelper = DbHelperFactory.GetHelper(BaseSystemInfo.UserCenterDbType, BaseSystemInfo.UserCenterDbConnection);
            AbandonIpaddressManager manager = new AbandonIpaddressManager(dbHelper, OperateContext.Current.UserInfo);
            if (manager.Delete(id) == 1)
            {
                baseResult.Status = true;
                baseResult.StatusMessage = "删除成功。";
                SecurityHelper.RemoveCacheAbandonIpAddressList();
            }
            else
            {
                baseResult.Status = false;
                baseResult.StatusMessage = "删除失败。";
            }

            return Json(baseResult, JsonRequestBehavior.AllowGet);
        }

        /// <summary>
        /// 批量删除受限的IP
        /// </summary>
        /// <param name="ids"></param>
        /// <returns></returns>
        public ActionResult DeleteIPBatch(string[] ids)
        {
            BaseResult baseResult = new BaseResult();
            baseResult.Status = false;
            IDbHelper dbHelper = DbHelperFactory.GetHelper(BaseSystemInfo.UserCenterDbType, BaseSystemInfo.UserCenterDbConnection);
            AbandonIpaddressManager manager = new AbandonIpaddressManager(dbHelper, OperateContext.Current.UserInfo);
            if (manager.Delete(ids) == 1)
            {
                baseResult.Status = true;
                baseResult.StatusMessage = "删除成功。";
                SecurityHelper.RemoveCacheAbandonIpAddressList();
            }
            else
            {
                baseResult.Status = false;
                baseResult.StatusMessage = "删除失败。";
            }
            return Json(baseResult, JsonRequestBehavior.AllowGet);
        }

    }

6、业务和实体底层代码使用了通用权限管理系统中的代码生成器生成;

技术分享

 业务层

技术分享
    /// <summary>
    /// AbabdonIpaddressManager
    /// 禁止访问系统的IP数据表
    /// 
    /// 修改纪录
    /// 
    /// 2015-10-10 版本:1.0 SongBiao 创建文件。
    /// 
    /// <author>
    ///     <name>SongBiao</name>
    ///     <date>2015-10-10</date>
    /// </author>
    /// </summary>
    public partial class AbandonIpaddressManager : BaseManager, IBaseManager
    {
        /// <summary>
        /// 构造函数
        /// </summary>
        public AbandonIpaddressManager()
        {
            if (base.dbHelper == null)
            {
                base.dbHelper = DbHelperFactory.GetHelper(BaseSystemInfo.UserCenterDbType, BaseSystemInfo.UserCenterDbConnection);
            }
            if (string.IsNullOrEmpty(base.CurrentTableName))
            {
                base.CurrentTableName = AbandonIpaddressEntity.TableName;
            }
            base.PrimaryKey = "Id";
        }

        /// <summary>
        /// 构造函数
        /// <param name="tableName">指定表名</param>
        /// </summary>
        public AbandonIpaddressManager(string tableName)
        {
            base.CurrentTableName = tableName;
        }

        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="dbHelper">数据库连接</param>
        public AbandonIpaddressManager(IDbHelper dbHelper)
            : this()
        {
            DbHelper = dbHelper;
        }

        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="userInfo">用户信息</param>
        public AbandonIpaddressManager(BaseUserInfo userInfo)
            : this()
        {
            UserInfo = userInfo;
        }

        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="userInfo">用户信息</param>
        /// <param name="tableName">指定表名</param>
        public AbandonIpaddressManager(BaseUserInfo userInfo, string tableName)
            : this(userInfo)
        {
            base.CurrentTableName = tableName;
        }

        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="dbHelper">数据库连接</param>
        /// <param name="userInfo">用户信息</param>
        public AbandonIpaddressManager(IDbHelper dbHelper, BaseUserInfo userInfo)
            : this(dbHelper)
        {
            UserInfo = userInfo;
        }

        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="dbHelper">数据库连接</param>
        /// <param name="userInfo">用户信息</param>
        /// <param name="tableName">指定表名</param>
        public AbandonIpaddressManager(IDbHelper dbHelper, BaseUserInfo userInfo, string tableName)
            : this(dbHelper, userInfo)
        {
            base.CurrentTableName = tableName;
        }

        /// <summary>
        /// 添加, 这里可以人工干预,提高程序的性能
        /// </summary>
        /// <param name="entity">实体</param>
        /// <param name="identity">自增量方式,表主键是否采用自增的策略</param>
        /// <param name="returnId">返回主键,不返回程序允许速度会快,主要是为了主细表批量插入数据优化用的</param>
        /// <returns>主键</returns>
        public string Add(AbandonIpaddressEntity entity, bool identity = true, bool returnId = true)
        {
            this.Identity = identity;
            this.ReturnId = returnId;
            entity.Id = this.AddObject(entity);
            return entity.Id.ToString();
        }

        /// <summary>
        /// 更新
        /// </summary>
        /// <param name="entity">实体</param>
        public int Update(AbandonIpaddressEntity entity)
        {
            return this.UpdateObject(entity);
        }

        /// <summary>
        /// 获取实体
        /// </summary>
        /// <param name="id">主键</param>
        public AbandonIpaddressEntity GetObject(string id)
        {
            return BaseEntity.Create<AbandonIpaddressEntity>(this.GetDataTable(new KeyValuePair<string, object>(this.PrimaryKey, id)));
            //return GetObject(id);
        }

        //public AbandonIpaddressEntity GetObject(int id)
        //{
        //    return BaseEntity.Create<AbandonIpaddressEntity>(this.GetDataTable(new KeyValuePair<string, object>(this.PrimaryKey, id)));
        //}

        /// <summary>
        /// 添加实体
        /// </summary>
        /// <param name="entity">实体</param>
        public string AddObject(AbandonIpaddressEntity entity)
        {
            string key = entity.Id;
            SQLBuilder sqlBuilder = new SQLBuilder(DbHelper, this.Identity, this.ReturnId);
            sqlBuilder.BeginInsert(this.CurrentTableName, this.PrimaryKey);
            if (!this.Identity)
            {
                // 这里已经是指定了主键了,所以不需要返回主键了
                sqlBuilder.ReturnId = false;
                sqlBuilder.SetValue(this.PrimaryKey, entity.Id);
            }
            else
            {
                if (!this.ReturnId && (DbHelper.CurrentDbType == CurrentDbType.Oracle || DbHelper.CurrentDbType == CurrentDbType.DB2))
                {
                    if (DbHelper.CurrentDbType == CurrentDbType.Oracle)
                    {
                        sqlBuilder.SetFormula(this.PrimaryKey, "SEQ_" + this.CurrentTableName.ToUpper() + ".NEXTVAL ");
                    }
                    if (DbHelper.CurrentDbType == CurrentDbType.DB2)
                    {
                        sqlBuilder.SetFormula(this.PrimaryKey, "NEXT VALUE FOR SEQ_" + this.CurrentTableName.ToUpper());
                    }
                }
                else
                {
                    if (this.Identity && (DbHelper.CurrentDbType == CurrentDbType.Oracle || DbHelper.CurrentDbType == CurrentDbType.DB2))
                    {
                        BaseSequenceManager sequenceManager = new BaseSequenceManager(DbHelper);
                        entity.Id = sequenceManager.Increment(this.CurrentTableName);
                        sqlBuilder.SetValue(this.PrimaryKey, entity.Id);
                    }
                }
            }
            this.SetObject(sqlBuilder, entity);
            if (UserInfo != null)
            {
                sqlBuilder.SetValue(AbandonIpaddressEntity.FieldCreateUserId, UserInfo.Id);
                sqlBuilder.SetValue(AbandonIpaddressEntity.FieldCreateBy, UserInfo.RealName);
            }
            else
            {
                sqlBuilder.SetValue(AbandonIpaddressEntity.FieldCreateBy, entity.CreateBy);
            }
            sqlBuilder.SetDBNow(AbandonIpaddressEntity.FieldCreateOn);
            if (UserInfo != null)
            {
                sqlBuilder.SetValue(AbandonIpaddressEntity.FieldModifiedUserId, UserInfo.Id);
                sqlBuilder.SetValue(AbandonIpaddressEntity.FieldModifiedBy, UserInfo.RealName);
            }
            sqlBuilder.SetDBNow(AbandonIpaddressEntity.FieldModifiedon);
            if (this.Identity && (DbHelper.CurrentDbType == CurrentDbType.SqlServer || DbHelper.CurrentDbType == CurrentDbType.Access))
            {
                key = sqlBuilder.EndInsert().ToString();
            }
            else
            {
                sqlBuilder.EndInsert();
            }
            if (this.Identity && (DbHelper.CurrentDbType == CurrentDbType.Oracle || DbHelper.CurrentDbType == CurrentDbType.DB2))
            {
                return entity.Id.ToString();
            }
            return key;
        }

        /// <summary>
        /// 更新实体
        /// </summary>
        /// <param name="entity">实体</param>
        public int UpdateObject(AbandonIpaddressEntity entity)
        {
            SQLBuilder sqlBuilder = new SQLBuilder(DbHelper);
            sqlBuilder.BeginUpdate(this.CurrentTableName);
            this.SetObject(sqlBuilder, entity);
            if (UserInfo != null)
            {
                sqlBuilder.SetValue(AbandonIpaddressEntity.FieldModifiedUserId, UserInfo.Id);
                sqlBuilder.SetValue(AbandonIpaddressEntity.FieldModifiedBy, UserInfo.RealName);
            }
            sqlBuilder.SetDBNow(AbandonIpaddressEntity.FieldModifiedon);
            sqlBuilder.SetWhere(this.PrimaryKey, entity.Id);
            return sqlBuilder.EndUpdate();
        }

        // 这个是声明扩展方法
        partial void SetObjectExpand(SQLBuilder sqlBuilder, AbandonIpaddressEntity entity);

        /// <summary>
        /// 设置实体
        /// </summary>
        /// <param name="entity">实体</param>
        private void SetObject(SQLBuilder sqlBuilder, AbandonIpaddressEntity entity)
        {
            SetObjectExpand(sqlBuilder, entity);
            sqlBuilder.SetValue(AbandonIpaddressEntity.FieldIpaddresstype, entity.IpAddressType);
            sqlBuilder.SetValue(AbandonIpaddressEntity.FieldDescription, entity.Description);
            sqlBuilder.SetValue(AbandonIpaddressEntity.FieldEnabled, entity.Enabled);
            sqlBuilder.SetValue(AbandonIpaddressEntity.FieldDeletionStateCode, entity.DeletionStateCode);
            sqlBuilder.SetValue(AbandonIpaddressEntity.FieldIpaddresscontent, entity.IpAddressContent);
        }

        /// <summary>
        /// 删除实体
        /// </summary>
        /// <param name="id">主键</param>
        /// <returns>影响行数</returns>
        public int Delete(int id)
        {
            return this.Delete(new KeyValuePair<string, object>(this.PrimaryKey, id));
        }
    }
View Code

实体层

技术分享
    /// <summary>
    /// AbabdonIpaddressEntity
    /// 禁止访问系统的IP数据表
    /// 
    /// 修改纪录
    /// 
    /// 2015-09-24 版本:1.0 SongBiao 创建文件。
    /// 
    /// <author>
    ///     <name>SongBiao</name>
    ///     <date>2015-09-24</date>
    /// </author>
    /// </summary>
    [Serializable]
    public partial class AbandonIpaddressEntity : BaseEntity
    {
        private string ipaddresstype = string.Empty;
        /// <summary>
        /// 类型:Single,Range,Mask
        /// </summary>
        public string IpAddressType
        {
            get
            {
                return ipaddresstype;
            }
            set
            {
                ipaddresstype = value;
            }
        }

        private DateTime? modifiedOn = null;
        /// <summary>
        /// 修改日期
        /// </summary>
        public DateTime? ModifiedOn
        {
            get
            {
                return modifiedOn;
            }
            set
            {
                modifiedOn = value;
            }
        }

        private string description = string.Empty;
        /// <summary>
        /// 描述信息
        /// </summary>
        public string Description
        {
            get
            {
                return description;
            }
            set
            {
                description = value;
            }
        }

        private Decimal enabled;
        /// <summary>
        /// 有效标志
        /// </summary>
        public Decimal Enabled
        {
            get
            {
                return enabled;
            }
            set
            {
                enabled = value;
            }
        }

        private string modifiedUserId = string.Empty;
        /// <summary>
        /// 修改用户主键
        /// </summary>
        public string ModifiedUserId
        {
            get
            {
                return modifiedUserId;
            }
            set
            {
                modifiedUserId = value;
            }
        }

        private string id = string.Empty;
        /// <summary>
        /// 主键
        /// </summary>
        public string Id
        {
            get
            {
                return id;
            }
            set
            {
                id = value;
            }
        }

        private string modifiedBy = string.Empty;
        /// <summary>
        /// 修改用户
        /// </summary>
        public string ModifiedBy
        {
            get
            {
                return modifiedBy;
            }
            set
            {
                modifiedBy = value;
            }
        }

        private string createBy = string.Empty;
        /// <summary>
        /// 创建用户
        /// </summary>
        public string CreateBy
        {
            get
            {
                return createBy;
            }
            set
            {
                createBy = value;
            }
        }

        private DateTime? createOn = null;
        /// <summary>
        /// 创建日期
        /// </summary>
        public DateTime? CreateOn
        {
            get
            {
                return createOn;
            }
            set
            {
                createOn = value;
            }
        }

        private Decimal? deletionStateCode = null;
        /// <summary>
        /// 删除标记
        /// </summary>
        public Decimal? DeletionStateCode
        {
            get
            {
                return deletionStateCode;
            }
            set
            {
                deletionStateCode = value;
            }
        }

        private string createUserId = string.Empty;
        /// <summary>
        /// 创建用户主键
        /// </summary>
        public string CreateUserId
        {
            get
            {
                return createUserId;
            }
            set
            {
                createUserId = value;
            }
        }

        private string ipaddresscontent = string.Empty;
        /// <summary>
        /// 具体IP内容 
        /// </summary>
        public string IpAddressContent
        {
            get
            {
                return ipaddresscontent;
            }
            set
            {
                ipaddresscontent = value;
            }
        }

        /// <summary>
        /// 从数据行读取
        /// </summary>
        /// <param name="dr">数据行</param>
        protected override BaseEntity GetFrom(IDataRow dr)
        {
            GetFromExpand(dr);
            IpAddressType = BaseBusinessLogic.ConvertToString(dr[AbandonIpaddressEntity.FieldIpaddresstype]);
            modifiedOn = BaseBusinessLogic.ConvertToNullableDateTime(dr[AbandonIpaddressEntity.FieldModifiedon]);
            Description = BaseBusinessLogic.ConvertToString(dr[AbandonIpaddressEntity.FieldDescription]);
            Enabled = BaseBusinessLogic.ConvertToDecimal(dr[AbandonIpaddressEntity.FieldEnabled]);
            modifiedUserId = BaseBusinessLogic.ConvertToString(dr[AbandonIpaddressEntity.FieldModifiedUserId]);
            Id = BaseBusinessLogic.ConvertToString(dr[AbandonIpaddressEntity.FieldId]);
            modifiedBy = BaseBusinessLogic.ConvertToString(dr[AbandonIpaddressEntity.FieldModifiedBy]);
            createBy = BaseBusinessLogic.ConvertToString(dr[AbandonIpaddressEntity.FieldCreateBy]);
            createOn = BaseBusinessLogic.ConvertToNullableDateTime(dr[AbandonIpaddressEntity.FieldCreateOn]);
            deletionStateCode = BaseBusinessLogic.ConvertToNullableDecimal(dr[AbandonIpaddressEntity.FieldDeletionStateCode]);
            createUserId = BaseBusinessLogic.ConvertToString(dr[AbandonIpaddressEntity.FieldCreateUserId]);
            IpAddressContent = BaseBusinessLogic.ConvertToString(dr[AbandonIpaddressEntity.FieldIpaddresscontent]);
            return this;
        }

        ///<summary>
        /// 禁止访问系统的IP数据表
        ///</summary>
        [NonSerialized]
        public static string TableName = "ABANDON_IPADDRESS";

        ///<summary>
        /// 类型:Single,Range,Mask
        ///</summary>
        [NonSerialized]
        public static string FieldIpaddresstype = "IPADDRESSTYPE";

        ///<summary>
        /// 修改日期
        ///</summary>
        [NonSerialized]
        public static string FieldModifiedon = "ModifiedOn";

        ///<summary>
        /// 描述信息
        ///</summary>
        [NonSerialized]
        public static string FieldDescription = "DESCRIPTION";

        ///<summary>
        /// 有效标志
        ///</summary>
        [NonSerialized]
        public static string FieldEnabled = "Enabled";

        ///<summary>
        /// 修改用户主键
        ///</summary>
        [NonSerialized]
        public static string FieldModifiedUserId = "ModifiedUserId";

        ///<summary>
        /// 主键
        ///</summary>
        [NonSerialized]
        public static string FieldId = "Id";

        ///<summary>
        /// 修改用户
        ///</summary>
        [NonSerialized]
        public static string FieldModifiedBy = "ModifiedBy";

        ///<summary>
        /// 创建用户
        ///</summary>
        [NonSerialized]
        public static string FieldCreateBy = "CreateBy";

        ///<summary>
        /// 创建日期
        ///</summary>
        [NonSerialized]
        public static string FieldCreateOn = "CreateOn";

        ///<summary>
        /// 删除标记
        ///</summary>
        [NonSerialized]
        public static string FieldDeletionStateCode = "DeletionStateCode";

        ///<summary>
        /// 创建用户主键
        ///</summary>
        [NonSerialized]
        public static string FieldCreateUserId = "CreateUserId";

        ///<summary>
        /// 具体IP内容 
        ///</summary>
        [NonSerialized]
        public static string FieldIpaddresscontent = "IPADDRESSCONTENT";
    }
View Code

 

7、IP限制功能前端展示,可根据自己的需要进行展示,可维护的IP有单个IP,IP段,掩码IP;

技术分享

 

技术分享

 

8、自动添加恶意访问的IP地址,这里给出一个参考,在通用权限底层里有一个恶意访问判断方法(可以拦截攻击者注入恶意代码,可以防御诸如跨站脚本攻击(XSS)、SQL注入攻击等恶意攻击行为。)

        protected void Application_AcquireRequestState(object sender, EventArgs e)
        {
            HttpContext context = HttpContext.Current;
            string putData;
            if (SecretUtil.CookieData(out putData))
            {
                ResponseWarnMessage(context, "Cookie数据有恶意字符!", putData);
            }
            if (Request.UrlReferrer != null)
            {
                if (SecretUtil.Referer(out putData))
                {
                    ResponseWarnMessage(context, "Referrer数据有恶意字符!", putData);
                }
            }
            if (Request.RequestType.ToUpper() == "POST")
            {
                if (SecretUtil.PostData(out putData))
                {
                    ResponseWarnMessage(context, "Post数据有恶意字符!", putData);
                }
            }
            if (Request.RequestType.ToUpper() == "GET")
            {
                if (SecretUtil.GetData(out putData))
                {
                    ResponseWarnMessage(context, "Get数据有恶意字符!", putData);
                }
            }
        }

在上面方法判断过程中就可以动态将恶意访问者的IP添加到限制访问列表中。

9、受限IP表结构

技术分享

SQL脚本

-- Create table
create table ABANDON_IPADDRESS
(
  ID                VARCHAR2(40),
  IPADDRESSTYPE     VARCHAR2(50),
  IPADDRESSCONTENT  VARCHAR2(200),
  DESCRIPTION       VARCHAR2(200),
  ENABLED           NUMBER(1) default 1 not null,
  DELETIONSTATECODE NUMBER(1) default 0,
  CREATEUSERID      VARCHAR2(50),
  CREATEBY          VARCHAR2(50),
  CREATEON          DATE,
  MODIFIEDON        DATE,
  MODIFIEDUSERID    VARCHAR2(50),
  MODIFIEDBY        VARCHAR2(50)
)
tablespace USERS
  pctfree 10
  initrans 1
  maxtrans 255
  storage
  (
    initial 64K
    next 1M
    minextents 1
    maxextents unlimited
  );
-- Add comments to the table 
comment on table ABANDON_IPADDRESS
  is 禁止访问系统的IP数据表;
-- Add comments to the columns 
comment on column ABANDON_IPADDRESS.ID
  is 主键;
comment on column ABANDON_IPADDRESS.IPADDRESSTYPE
  is 类型:Single,Range,Mask;
comment on column ABANDON_IPADDRESS.IPADDRESSCONTENT
  is 具体IP内容 ;
comment on column ABANDON_IPADDRESS.DESCRIPTION
  is 描述信息;
comment on column ABANDON_IPADDRESS.ENABLED
  is 有效标志;
comment on column ABANDON_IPADDRESS.DELETIONSTATECODE
  is 删除标记;
comment on column ABANDON_IPADDRESS.CREATEUSERID
  is 创建用户主键;
comment on column ABANDON_IPADDRESS.CREATEBY
  is 创建用户;
comment on column ABANDON_IPADDRESS.CREATEON
  is 创建日期;
comment on column ABANDON_IPADDRESS.MODIFIEDON
  is 修改日期;
comment on column ABANDON_IPADDRESS.MODIFIEDUSERID
  is 修改用户主键;
comment on column ABANDON_IPADDRESS.MODIFIEDBY
  is 修改用户;

 

Web应用限制IP访问功能的实现

标签:

原文地址:http://www.cnblogs.com/hnsongbiao/p/4867299.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!