MVC中使用AuthorizeAttribute做身分識別驗證操作

來源:互聯網
上載者:User

標籤:

代碼順序為: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);              }    }

 

MVC中使用AuthorizeAttribute做身分識別驗證操作

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.