1. 程式人生 > >MVC中使用AuthorizeAttribute身份驗證

MVC中使用AuthorizeAttribute身份驗證

程式碼順序為:OnAuthorization-->AuthorizeCore-->HandleUnauthorizedRequest

如果AuthorizeCore返回false時,才會走HandleUnauthorizedRequest 方法,並且Request.StausCode會返回401,401錯誤又對應了Web.config中

所有,AuthorizeCore==false 時,會跳轉到 web.config 中定義的 loginUrl="login/login"

AuthorizeAttribute的OnAuthorization方法內部呼叫了AuthorizeCore方法,這個方法是實現驗證和授權邏輯的地方,如果這個方法返回true,表示授權成功,如果返回false, 表示授權失敗,會給上下文設定一個HttpUnauthorizedResult,這個ActionResult執行的結果是向瀏覽器返回一個401狀態碼(未授權),但是返回狀態碼沒什麼意思,通常是跳轉到一個登入頁面,可以重寫AuthorizeAttribute的HandleUnauthorizedRequest


<authentication mode="Forms">
      <forms loginUrl="login/login" timeout="2880" />
</authentication>
[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, AllowMultiple = false)]
    public class UserAuthorizeAttribute : AuthorizeAttribute
    {
        protected override bool AuthorizeCore(HttpContextBase httpContext)
        {
            var user = (SysUser)httpContext.Session["CurrentUser"];
            return user != null;
        }

        protected override void HandleUnauthorizedRequest(AuthorizationContext filterContext)
        {
            if (filterContext.HttpContext.Request.IsAjaxRequest())
            {
                var a = new JsonResult();
                a.Data = new AjaxResult() { Message = "會話已過期,請重新登入" };
                filterContext.Result = a;
                return;
            }
            filterContext.Result = new RedirectResult("/Login/Login?url=" + filterContext.HttpContext.Request.Url);

        }
    }