2011-01-20 28 views
3

我試圖從web服務中存儲一整個關於用戶的信息。由於這是關於當前通過身份驗證的用戶的信息,我認爲將這些信息存儲在自定義IIdentity實現中是有意義的。MVC2 ::我如何*使用*自定義IIdentity類?

自定義MagicMembershipProvider.GetUser(string id, bool userIsOnline)調用webservice並返回一個MagicMembershipUser實例,其中包含所有填充的字段(部門,電話號碼和其他員工信息)。

自定義成員資格提供程序和自定義成員資格用戶都正常工作。

什麼其中是把會員用戶信息到IPrincipal User對象,它是在每個控制器可訪問的最佳方式?

我一直試圖圍繞MVC2應用程序中的IIdentity,IPrincipal和Role授權的安全程序流程大腦 - 但我在這裏真的很苦惱,可以使用一些指導。有關於部件的Internet Ton文章,但對整體而言並不多。

編輯

我最好的猜測,到目前爲止是分配HttpContext.Current.UserFormsAuthenticationService

public void SignIn(string userName, bool createPersistentCookie) 
{ 
    if (String.IsNullOrEmpty(userName)) 
    throw new ArgumentException("Value cannot be null or empty.", "userName"); 

    try 
    { 
    FormsAuthentication.SetAuthCookie(userName, createPersistentCookie); 
    MagicMembershipUser magicUser = _provider.GetUser("", false) 
     as MagicMembershipUser; 
    MagicIdentity identity = new MagicIdentity(userName, magicUser); 
    GenericPrincipal principal = new GenericPrincipal(identity, null); 

    HttpContext.Current.User = principal; 
    } 
    catch (Exception) 
    { 
    throw; 
    } 

    } 

回答

1

哪些地方是把會員用戶信息到的IPrincipal User對象的最佳方式每個控制器都可以訪問?

在自定義[Authorize]過濾器實現。您可以覆蓋AuthorizeCore方法並調用基本方法,如果它返回true,則查詢您的成員資格提供程序並將自定義魔法標識注入上下文。

例子:

public class MagicAuthorizeAttribute : AuthorizeAttribute 
{ 
    protected override bool AuthorizeCore(HttpContextBase httpContext) 
    { 
     var isAuthorized = base.AuthorizeCore(httpContext); 
     if (isAuthorized) 
     { 
      var username = httpContext.User.Identity.Name; 
      var magicUser = _provider.GetUser(username, false) as MagicMembershipUser; 
      var identity = new MagicIdentity(username, magicUser); 
      var principal = new GenericPrincipal(identity, null); 
      httpContext.User = principal; 
     } 
     return isAuthorized; 
    } 
} 

現在,所有剩下的就是裝飾用[MagicAuthorize]屬性的基本控制器。

+0

我注意到_provider沒有實例 - 爲什麼? – 2011-01-21 18:40:09

相關問題