程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
 程式師世界 >> 編程語言 >> .NET網頁編程 >> 關於.NET >> ASP.NET MVC中利用AuthorizeAttribute實現訪問身份是否合法以及Cookie過期問題的處理,

ASP.NET MVC中利用AuthorizeAttribute實現訪問身份是否合法以及Cookie過期問題的處理,

編輯:關於.NET

ASP.NET MVC中利用AuthorizeAttribute實現訪問身份是否合法以及Cookie過期問題的處理,


話說來到上海已經快半年了,時光如白駒過隙,稍微不注意,時間就溜走了,倒是沒有那麼忙碌,閒暇之際來博客園還是比較多的,記得上次在逛博問的時候看到有同志在問MVC中Cookie過期後如何作相關處理,他在闡述那麼多頁面不可能都去一個個手動處理。其實MVC很牛逼的地方就是把Attribute利用的非常完美,接下來就來看下它是如何做到的吧!

第一步、我們要定義一個登錄過濾標簽-LoginFilterAttribute並且繼承AuthorizeAttribute。來看下它內部是啥樣子

 1 // Summary:
 2     //     Represents an attribute that is used to restrict access by callers to an
 3     //     action method.
 4     [AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, Inherited = true, AllowMultiple = true)]
 5     public class AuthorizeAttribute : FilterAttribute, IAuthorizationFilter
 6     {
 7         // Summary:
 8         //     Initializes a new instance of the System.Web.Mvc.AuthorizeAttribute class.
 9         public AuthorizeAttribute();
10 
11         // Summary:
12         //     Gets or sets the user roles.
13         //
14         // Returns:
15         //     The user roles.
16         public string Roles { get; set; }
17         //
18         // Summary:
19         //     Gets the unique identifier for this attribute.
20         //
21         // Returns:
22         //     The unique identifier for this attribute.
23         public override object TypeId { get; }
24         //
25         // Summary:
26         //     Gets or sets the authorized users.
27         //
28         // Returns:
29         //     The authorized users.
30         public string Users { get; set; }
31 
32         // Summary:
33         //     When overridden, provides an entry point for custom authorization checks.
34         //
35         // Parameters:
36         //   httpContext:
37         //     The HTTP context, which encapsulates all HTTP-specific information about
38         //     an individual HTTP request.
39         //
40         // Returns:
41         //     true if the user is authorized; otherwise, false.
42         //
43         // Exceptions:
44         //   System.ArgumentNullException:
45         //     The httpContext parameter is null.
46         protected virtual bool AuthorizeCore(HttpContextBase httpContext);
47         //
48         // Summary:
49         //     Processes HTTP requests that fail authorization.
50         //
51         // Parameters:
52         //   filterContext:
53         //     Encapsulates the information for using System.Web.Mvc.AuthorizeAttribute.
54         //     The filterContext object contains the controller, HTTP context, request context,
55         //     action result, and route data.
56         protected virtual void HandleUnauthorizedRequest(AuthorizationContext filterContext);
57         //
58         // Summary:
59         //     Called when a process requests authorization.
60         //
61         // Parameters:
62         //   filterContext:
63         //     The filter context, which encapsulates information for using System.Web.Mvc.AuthorizeAttribute.
64         //
65         // Exceptions:
66         //   System.ArgumentNullException:
67         //     The filterContext parameter is null.
68         public virtual void OnAuthorization(AuthorizationContext filterContext);
69         //
70         // Summary:
71         //     Called when the caching module requests authorization.
72         //
73         // Parameters:
74         //   httpContext:
75         //     The HTTP context, which encapsulates all HTTP-specific information about
76         //     an individual HTTP request.
77         //
78         // Returns:
79         //     A reference to the validation status.
80         //
81         // Exceptions:
82         //   System.ArgumentNullException:
83         //     The httpContext parameter is null.
84         protected virtual HttpValidationStatus OnCacheAuthorization(HttpContextBase httpContext);
85     }

這裡我們要重寫OnAuthorization這個方法。

接下來就看下LoginFilterAttibute這個"兒子"是怎麼完成"老子"交待的任務了。直接上code

 1 public class LoginFilterAttribute:AuthorizeAttribute
 2     {
 3 
 4         private static string formsCookieName = FormsAuthentication.FormsCookieName;
 5 
 6         public override void OnAuthorization(AuthorizationContext filterContext)
 7         {
 8            HttpCookie formsCookie =
 9                 System.Web.CookieManager.GetCookie(formsCookieName);
10             if (formsCookie == null)
11             {
12                 //頁面Cookie過期後返回登錄頁面
13                 RedirectToLoginPage(filterContext);
14                 return;
15             }
16  
17             bool autenticated = HttpContext.Current.User.Identity.IsAuthenticated;
18 
19             //一旦發現身份不合法就作相應的處理.
20             if (!autenticated )
21             {
22                 //redirect to login
23                 RedirectToLoginPage(filterContext);
24                 return;
25             }
26             //if success add login data to context
27         }
28            private static void RedirectToLoginPage(AuthorizationContext filterContext)
29         {
30             if (filterContext.HttpContext.Request.IsAjaxRequest())
31             {
32                 filterContext.Result = new JsonResult() 
33                 { 
34                     Data = new {
35                         status = "error",
36                         message = "Unauthorized_Message"
37                     },
38                     JsonRequestBehavior= JsonRequestBehavior.AllowGet
39                 };
40                 return;
41             }
42 else
43 {
44          //返回登錄頁面的相關處理..........
45 }
}

第二步、新建一個基類Controller-BaseController並且繼承Controller。

1     [LoginFilter]//此處就是我們上面定義的LoginFilterAttribute
2     public abstract partial class BaseController : Controller
3     {
4         public BaseController(){ 
5         
6         }
7       //........其他相關處理
8     }

第三步、不是有很多頁面嗎?那我只要在對應的Controller去繼承那個BaseController就實現了,在訪問任何一個頁面都會去作相應的過濾和處理。

1 Public Class LoginController:BaseController
2 {
3      Public ActionResult Index()
4     {
5       //........
6        return  View();
7     }
8 }

以上純屬個人觀點,如有雷同純屬巧合!謝謝閱讀,如果對您有幫助,請點關注並推薦!

  1. 上一頁:
  2. 下一頁:
Copyright © 程式師世界 All Rights Reserved