2009-12-01 124 views
5

我想使用AuthorizeAttribute控制哪些用戶可以訪問我的操作。我只是想澄清一下,我的邏輯是正確的。ASP.Net MVC成員資格

  1. 創建我自己的實現的IPrincipal
  2. 我發佈用戶的憑據安全控制器的登錄操作。
  3. 我驗證了UserService類的憑據和分配的IPrincipal從我UserService類返回到HttpContext.User中
  4. 我WebAuthorizeAttribute,它繼承AuthorizeAttribute,檢查當前HttpContext.User.Identity.IsAuthenticated和HttpContext.User.IsInRole以確定用戶是否有權訪問該操作。

事情是否正常?我知道我可以繼承MembershipProvider,但我並不需要所有的功能,實際上只是能夠使用兩種不同的角色登錄。

回答

4

您必須在某處存儲IPrincipal,並在每次請求時恢復它。如果你使用FormsAuthentication,這是很好的解決方案:

ASP.NET 2.0 Forms authentication - Keeping it customized yet simple

,你可以在這裏找到其他的解決辦法:

Where to store logged user information on ASP.NET MVC using Forms Authentication?

和propably在許多其他StackOverflow的問題:)

編輯

關於MyBusinessLayerSecurityClass.CreatePrincipal(ID,id.Name):

你應該閱讀此頁:

http://msdn.microsoft.com/en-us/library/aa480476.aspx

特別是:

FormsAuthenticationModule 類構造一個 GenericPrincipal object and st將其存儲在HTTP 上下文中。所述 的GenericPrincipal 對象保存到表示當前 認證的用戶一個 FormsIdentity 實例的引用。您應該允許 表單身份驗證來爲您管理這些 任務。如果您的應用程序 有特定的要求,比如 的用戶 屬性設置爲自定義類 實現 的IPrincipal接口, 您的應用程序應該處理 PostAuthenticate 事件。該 PostAuthenticate 事件發生 FormsAuthenticationModule後 已經驗證了窗體身份驗證 cookie,並創造了 的GenericPrincipalFormsIdentity 對象。在此代碼,可以 構建自定義 的IPrincipal對象 一個包裝 FormsIdentity對象, 然後將其存儲在 的HttpContext。用戶 屬性。

FormsIdentity自動管理後,您設置身份驗證cookie。你所要做的就是把它包裝在你的IPrincipal中。所有這些都發生在HttpContext.Current.User屬性不爲空(它是GenericPrincipal,你不久之後替換)。當HttpContext.Current.User爲空時,以前沒有創建身份驗證cookie,並且用戶未經過身份驗證。

+0

我已經閱讀了很多問題和外部博客,但沒有人真的把這整個部分放到上下文中。你可以解釋一下MyBusinessLayerSecurityClass.CreatePrincipal(id,id.Name)部分的 – scottm 2009-12-01 23:56:13

+0

。如果HttpContext.Current.User屬性爲null,我不明白如何獲取FormsIdentity。 – scottm 2009-12-02 02:12:26

2

我相信以下是比較典型的:

  1. 創建我自己的實現的IPrincipal
  2. 我發佈用戶的憑據安全控制器的登錄操作。
  3. 我驗證憑據與UserService類和構建具有此用戶某些標識信息的cookie。通常使用FormsAuthentication.SetAuthCookie或該類的實用程序方法的某種組合。
  4. 在Application AuthenticateRequest事件中,檢查cookie並分配Context.User。注意:在AuthenticateRequest事件之後,此值將自動分配給Thread.CurrentPrincipal。這是一次性賦值,這些值此後不會自動同步。
  5. 我的WebAuthorizeAttribute繼承了AuthorizeAttribute,它檢查當前的HttpContext.User.Identity.IsAuthenticated和HttpContext.User.IsInRole以確定用戶是否有權訪問該操作。
+1

+1:這也是我所做的。我的文章解釋瞭如何檢查cookie。 – LukLed 2009-12-02 00:14:10

+0

優秀,感謝您的參與 – scottm 2009-12-02 01:56:27