2010-10-14 21 views
2

我需要能夠手動授權我的控制器中的用戶。
我得到我的認證,從一個廣告,然後在我的控制器,
我想將我從AD得到的userID映射到我的應用程序的內部用戶ID。
從UserRole表中獲取userId,然後將其設置在控制器中,但是,
我不知道如何在控制器中設置角色?在控制器中設置用戶角色?

我試着在我的家鄉控制器這樣做:
HttpContext.User中=新System.Security.Principal.GenericPrincipal(User.Identity,角色名);

roleName設置爲「管理員」,但這似乎不起作用,因爲它總是失敗授權。 ?

請幫助....

回答

3

假設你正在使用您的控制器方法[Authorize],這將之前運行的操作方法,因此不會達到你要設置的角色名稱的代碼 - 它需要在調用控制器之前設置。

添加這樣的方法來你的Global.asax:

protected void Application_OnPostAuthenticateRequest(Object sender, EventArgs e) 
{ 
    IPrincipal contextUser = Context.User; 

    if (contextUser.Identity.AuthenticationType == "Forms") 
    { 
     // determine role name 

     // attach to context 
     HttpContext.Current.User = new System.Security.Principal.GenericPrincipal(User.Identity, roleName); 
     Thread.CurrentPrincipal = HttpContext.Current.User; 
    } 
} 
+0

嗨Clicktricity,感謝您的答覆。我認爲這是行不通的,因爲我使用ADFS來認證我的用戶。因此,我的身份驗證模式不是基於表單的,因此「if」語句將始終爲假。我錯了嗎? – TriFu 2010-10-14 16:33:16

+0

公平 - 只是適應您的需求。關鍵在於當前用戶分配在OnPostAuthenticationRequest期間發生 – Clicktricity 2010-10-14 19:10:53

+0

在您嘗試訪問某些控制器時,此方法是否總是檢查用戶的角色?沒有辦法將用戶的角色存儲在某種會話對象或cookie中?那樣你不需要總是爲用戶的角色選擇數據庫? – TriFu 2010-10-14 19:35:07

相關問題