zoukankan      html  css  js  c++  java
  • MVC扩展Filter, 通过继承AuthorizationAttribute限制IP

      为什么需要AuthorizationAttribute

    在没有Authorization系统属性之前,我们可能这样判断:
    Request.IsAuthenticated && User.Identity.IsAuthenticated来判断请求是否有权限。

    有了Authorization系统属性之后,我们可能这样:
    [Authorize]
    public ActionResult SomeAction()

    在Web.config文件中:
    <authentication mode="Forms">
        <forms loginUrl="~/Home/UnAuthorized" timeout="2880" />
    </authentication>

    很显然,有了AuthorizeAttribute这种cross-cutting设计,简化了代码,降低了耦合。

      通过继承AuthorizationAttribute来扩展

    主要是重写AuthorizeCore方法。

    public class SomeAuthorizationAttribute : AuthorizeAttribute
    {
        private List<string> blockIps;
        protected override bool AuthorizeCore(HttpContextBase httpContext)
        {
            LoadBockIpAddresses();
            return (!blockIps.Contains(httpContext.Request.UserHostAddress));
        }
     
        public void LoadBlockIpAddresses()
        {
            blokedIps = new List<string>();
            blockedIps.Add("127.0.0.1");
        }
    }

      使用默认的AuthorizeAttribute

    [Authorize(Users="", Roles="")]
    public ActionResult SomeAction

    同时需要在Web.config中配置:

    <authentication mode="Forms">
      <forms loginUrl="~/Home/UnAuthorized" timeout="2880">
        <credentials>
          <user name="name" password="name"/>
        </credentials>
      </forms>
    </authentication>
    <roleManager enabled="true" cacheRolesInCookie="true" />

    参考资料:
    MVC Filters Part 1 - Authorization Filter

  • 相关阅读:
    HDU 1251 统计难题 字符匹配
    mac 安装mysql
    ubuntu git 下添加 ssh
    mac下virtualenv使用
    git-ssh配置和使用
    在PythonAnyWhere上部署Django项目
    ImportError: No module named PIL
    mysql 命令行操作
    ubuntu安装ssh
    常用git命令
  • 原文地址:https://www.cnblogs.com/darrenji/p/3754147.html
Copyright © 2011-2022 走看看