zoukankan      html  css  js  c++  java
  • MVC中使用AuthorizeAttribute做身份验证操作

    代码顺序为:OnAuthorization-->AuthorizeCore-->HandleUnauthorizedRequest

    如果AuthorizeCore返回false时,才会走HandleUnauthorizedRequest 方法,并且Request.StausCode会返回401,401错误又对应了Web.config中的:

    <authentication mode="Forms">
         <forms loginUrl="~/" timeout="2880" />
    </authentication>

    所有,AuthorizeCore==false 时,会跳转到 web.config 中定义的  loginUrl="~/"

    [AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, AllowMultiple = false, Inherited = true)]
    public
    class CheckLoginAttribute : AuthorizeAttribute { protected override bool AuthorizeCore(HttpContextBase httpContext) { bool Pass = false; if (!CheckLogin.AdminLoginCheck()) { httpContext.Response.StatusCode = 401;//无权限状态码 Pass = false; } else { Pass = true; } return Pass; }
         protected override void OnAuthorization(AuthorizationContext filterContext)
         {
             base.OnAuthorization(filterContext);
         }
    protected override void HandleUnauthorizedRequest(AuthorizationContext filterContext) { base.HandleUnauthorizedRequest(filterContext); if (filterContext.HttpContext.Response.StatusCode == 401) { filterContext.Result = new RedirectResult("/"); } }
    }

    AuthorizeAttribute的OnAuthorization方法内部调用了AuthorizeCore方法,这个方法是实现验证和授权逻辑的地方,如果这个方法返回true,表示授权成功,如果返回false, 表示授权失败, 会给上下文设置一个HttpUnauthorizedResult,这个ActionResult执行的结果是向浏览器返回一个401状态码(未授权),但是返回状态码没什么意思,通常是跳转到一个登录页面,可以重写AuthorizeAttribute的HandleUnauthorizedRequest

    protected override void HandleUnauthorizedRequest(AuthorizationContext context)  
    {  
        if (context == null)  
        {  
            throw new ArgumentNullException("filterContext");  
        }  
         else  
        {  
            string path = context.HttpContext.Request.Path;  
            string strUrl = "/Account/LogOn?returnUrl={0}";  
            
            context.HttpContext.Response.Redirect(string.Format(strUrl, HttpUtility.UrlEncode(path)), true);          
        }    
    }
  • 相关阅读:
    hdu5608 function
    Codeforces Round #535 (Div. 3) 解题报告
    HDU4746 Mophues
    HDU5663 Hillan and the girl
    AtCoder Beginner Contest 117 解题报告
    GDOI2018D2T1 谈笑风生
    BZOJ4018: 小Q的幻想之乡
    牛客寒假算法基础集训营6 解题报告
    win32拖拽编程
    项目开发中的贝塞尔曲线
  • 原文地址:https://www.cnblogs.com/sky-net/p/4294576.html
Copyright © 2011-2022 走看看