2012-01-25 15 views
2

我需要找到誰是當前用戶並在活動目錄設置(Windows Server 2008)中檢查他們的組以查看他們是否有權訪問mvc3站點上的某些頁面(管理員)我正在構建。但是,無論何時創建PrincipalContext並查詢當前用戶,它都會返回網站運行的應用程序池。UserPrincipal.Current返回IIS上的應用程序池

我用盡:

PrincipalContext ctx = new PrincipalContext(ContextType.Domain); 
UserPrincipal currentuser = UserPrincipal.Current; 
string username = currentuser.DisplayName; 

PrincipalContext ctx = new PrincipalContext(ContextType.Domain, "domain", "CN=dbcn LDAP,OU=the - account,DC=thedc,DC=local", "domain\\user", "password"); 
UserPrincipal currentuser = UserPrincipal.Current; 
string username = currentuser.DisplayName; 

Web.config文件看起來像:

伊夫試圖用兩個不同的帳戶實例化上下文(並且沒有帳號指定

<configuration> 
<appSettings> 
<add key="webpages:Version" value="1.0.0.0" /> 
<add key="ClientValidationEnabled" value="true" /> 
<add key="UnobtrusiveJavaScriptEnabled" value="true" /> 
<add key="autoFormsAuthentication" value="false" /> 
<add key="enableSimpleMembership" value="false"/> 
</appSettings> 
<authentication mode="Windows" /> 
<membership defaultProvider="AspNetActiveDirectoryMembershipProvider"> 
<providers> 
<clear /> 
<add name="AspNetActiveDirectoryMembershipProvider" type="System.Web.Security.ActiveDirectoryMembershipProvider, System.Web, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" connectionStringName="service" /> 
</providers> 
</membership> 
<roleManager enabled="true" defaultProvider="AspNetWindowsTokenRoleProvider"> 
<providers> 
<clear /> 
<add name="AspNetWindowsTokenRoleProvider" type="System.Web.Security.WindowsTokenRoleProvider" applicationName="/" /> 
</providers> 
</roleManager> 
<identity impersonate="false" /> 
<connectionStrings> 
<add name="foocontext" connectionString="data source=foo;Initial Catalog=foo;Integrated Security=SSPI;MultipleActiveResultSets=true;" providerName="System.Data.SqlClient" /> 
<add name="ADService" connectionString="LDAP://foo.local/OU=the - service,DC=foo,DC=local" /> 
</connectionStrings> 
</configuration> 
),其中一個是IT管理員用於查詢的ldap帳戶。我在這裏錯過了什麼?爲什麼它總是以當前用戶的身份返回apppool?我如何獲取當前登錄的用戶。

謝謝!

回答

2

HttpContext.User中是你想要的...

在ASP.NET中,進行身份驗證的Windows身份驗證的用戶的安全上下文由WindowsPrincipal和的WindowsIdentity類的代表。使用Windows身份驗證的ASP.NET應用程序可以通過HttpContext.User屬性訪問WindowsPrincipal類。

要檢索發起當前請求的身份驗證的Windows用戶的安全上下文中,使用下面的代碼:

使用System.Security.Principal; ... //獲取經過身份驗證的用戶身份 WindowsPrincipal winPrincipal =(WindowsPrincipal)HttpContext.Current.User;

Asp.Net Windows Auth

+1

好什麼工作。我不能使用當前(不可用),我得到了一個鑄造錯誤,但'string winPrincipalName = HttpContext.User.Identity.Name; '確實給了我正確的用戶。現在,我如何確定用戶是哪個AD組的成員? findbyidentity總是給我空結果。 – user1168607

0

這是我經過一番搜索

PrincipalContext ctx = new PrincipalContext(ContextType.Domain); 
UserPrincipal user = UserPrincipal.FindByIdentity(ctx, User.Identity.Name);