2011-05-18 130 views
15

我想在我的ASP.NET MVC2應用程序中實現Windows身份驗證。 我已經按照由官方文檔建議的所有步驟:ASP.NET MVC和Windows身份驗證與自定義角色

<authentication mode="Windows" /> 

<authorization> 
    <deny users="?" /> 
</authorization> 

我指定NTLM身份驗證。到現在爲止還挺好。一切正常。 我想檢查用戶登錄我的數據庫。 我想從我的表中獲取角色,然後使用自定義屬性管理授權。
我不想使用成員資格和角色提供者。 我已經擁有我的表用戶/角色就位導致他們已經用於Internet應用程序(這是Intranet應用程序)。

在我的互聯網應用我有在用戶輸入數據的形式。表單發佈到控制器,該控制器檢查所有內容並與登錄用戶的用戶(和角色)創建一個cookie。

在我的Global.asax我被困在AuthenticateRequest事件,我讀的cookie和創造,我用遍應用程序檢查授權自定義主體。

我該如何使用Windows身份驗證來實現這一點?

回答

23

只需創建一個新的主體,並將其分配給在Global.asax中的用戶和線程(或使用行爲過濾器)。

protected void Application_AuthenticateRequest(object sender, EventArgs args) 
{ 
    if(HttpContext.Current != null) 
    { 
    String [] roles = GetRolesFromSomeDataTable(HttpContext.Current.User.Identity.Name); 

    GenericPrincipal principal = new GenericPrincipal(HttpContext.Current.User.Identity, roles); 

    Thread.CurrentPrincipal = HttpContext.Current.User = principal; 
    } 
} 

如果用戶沒有任何匹配的角色,他們可以從應用程序使用的web.config authoirzation元素禁止:

<authorization> 
    <allow roles="blah,whatever"/> 
    <deny users="*"/>    
</authorization> 
+0

@Xhalent:是的,但是...哪裏...? – LeftyX 2011-05-18 10:41:18

+0

我希望我已經澄清了它 – Xhalent 2011-05-18 11:14:30

+0

@Xhalent:感謝您的幫助。現在看起來很清楚。如果用戶未被授權訪問整個應用程序(它不在數據庫中),你會怎麼做? – LeftyX 2011-05-18 11:19:48

6

只需添加到上面的回答,希望這節省了一些時間。

我有一個內聯網MVC 5個網站與VS 2015

,直到頂線與HttpContext.Current.User更新的代碼並沒有爲我工作。如果用戶尚未在數據庫中創建,該網站將爲我提供對HttpContext.Current.User的空引用。通過將.User添加到第一行,它在第一次加載時繞過該代碼並工作。

if (HttpContext.Current.User != null) 
     { 


      String[] roles = GetRolesFromSomeDataTable(HttpContext.Current.User.Identity.Name); 

      GenericPrincipal principal = new GenericPrincipal(HttpContext.Current.User.Identity, roles); 

      Thread.CurrentPrincipal = HttpContext.Current.User = principal; 
     } 
相關問題