6

我試圖讓ActiveDirectory和標準表單登錄工作,但有一件事是阻止我。我無法獲取當前Windows用戶的名稱。我得到的最接近var i = WindowsIdentity.GetCurrent();,但是這給了我IIS應用程序池用戶的名字。我在IIS中啓用了匿名身份驗證,表單身份驗證和Windows身份驗證。我可以從AD加載用戶,所以我認爲我的web.config安裝正確。ActiveDirectory在ASP.NET中的當前用戶名

編輯:這是我的web.config(使用門面提供商):

<membership defaultProvider="HybridMembershipProvider"> 
     <providers> 
     <clear /> 
     <add name="HybridMembershipProvider" type="MyApp.Data.HybridMembershipProvider" AspNetProviderName="AspNetSqlMembershipProvider" ActiveDirectoryProviderName="ADMembershipProvider" /> 
     <add name="AspNetSqlMembershipProvider" type="System.Web.Security.SqlMembershipProvider" connectionStringName="MyAppConnection" enablePasswordRetrieval="false" enablePasswordReset="true" requiresQuestionAndAnswer="false" requiresUniqueEmail="false" maxInvalidPasswordAttempts="5" minRequiredPasswordLength="4" minRequiredNonalphanumericCharacters="0" passwordAttemptWindow="10" applicationName="/" /> 
     <add name="ADMembershipProvider" type="System.Web.Security.ActiveDirectoryMembershipProvider, System.Web, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" connectionStringName="ADConnectionString" 
      attributeMapUsername="sAMAccountName" enableSearchMethods="true" attributeMapEmail="mail"/> 
     </providers> 
    </membership> 

編輯2:這是我的IIS安全設置。

IIS Security setup

回答

4

如果您在IIS中啓用ASP.Net模擬,則可以獲得您想要的用戶名,只有在該數據位於表單成員資格提供程序/ AD中, 和他們不是匿名的。

此外,混合基於表單和Windows/AD基於身份驗證是可行的,但不推薦使用。見this如果你需要做到這一點。

編輯:我想我誤解你想要什麼,所以這裏有一個高層次的東西與上述方案繼續粉飾:

如果關閉匿名身份驗證,並打開Asp.Net假冒每當有人訪問該網站IIS會做一個401的挑戰。
如果一切都在同一個域中,Web瀏覽器會將您的憑據發送給IIS,IIS將根據它的Active Directory對它們進行驗證,然後AD將爲IIS提供身份驗證。

當您打開Asp.Net模擬時,IIS會將該標識綁定到當前線程/請求。驗證操作後,您可以隨意在當前線程身份的用戶名,然後查詢Active Directory,如:

Context.User.Identity.Name 

using System.Threading; 
using System.DirectoryServices; 
using System.DirectoryServices.AccountManagement; 

...... 

PrincipalContext pc = null; 
UserPrincipal principal = null; 

try 
{ 
    var username = Thread.CurrentPrincipal.Identity.Name; 
    pc = new PrincipalContext(ContextType.Domain, "active.directory.domain.com"); 
    principal = UserPrincipal.FindByIdentity(pc, username); 

    var firstName = principal.GivenName ?? string.Empty 
    var lastName = principal.Surname ?? string.Empty 
    return string.Format("Hello {0} {1}!", firstName, lastName); 
} 
catch ... 
finally 
{ 
    if (principal != null) principal.Dispose(); 
    if (pc != null) pc.Dispose(); 
} 
+0

你能解釋一下你的前兩點嗎?你的意思是「如果這些數據在表格會員提供者/ AD中」。他們是一個用戶,我可以通過用戶名查詢AD。 「 」否則,你將不得不查詢AD來獲取他們的名字。「 - 我可以做到這一點,如果我有他們的名字,但我該怎麼做才能得到他們的名字? – Echilon

+0

爲您編輯的答案,請再閱讀 –

+0

我遇到的問題是'Thread.CurrentPrincipal.Identity.Name '爲空,我無法獲取用戶名。 – Echilon

-1

我給一個嘗試:

var i = Environment.CurrentUser;

,你也可以用我的課: http://pastebin.com/xnYfVsLX

+0

我不認爲這會工作的網絡應用程序,我假設這是自他提到的形式auth – Eonasdan

1

在.NET應用程序,我寫,我已經使用Windows身份驗證我仍然可以使用User.Identity.Name獲取AD用戶名。當然,這通常包括DC,並返回用戶SAM帳戶名稱。我沒有試圖同時實現,但User.Identity.Name肯定單獨工作

0

這是我在ASP.NET MVC應用程序中使用的一段代碼,不久前它幫助了我,不知道如果它會幫助你,雖然,你可以自由地檢查,雖然

private static void CheckIfUserExists(string p) 
    { 
     try 
     { 
       var user = (from x in Data.EntityDB.UserInfoes where x.SAMAccountName == p select x).FirstOrDefault(); 
       DirectoryEntry entry = new DirectoryEntry(Properties.Settings.Default.LDAPPath); //this is the connection to your active directory 
       DirectorySearcher search = new DirectorySearcher(entry); 
       search.PropertiesToLoad.Add("*"); 
       search.Filter = "(&(sAMAccountName=" + p + ")(objectCategory=person))"; 
       SearchResult searchResult = search.FindOne(); 
      //If the user under the alias is not found, Add a new user. Else, update his current data 
      if (user == null) 
      { 
       XXXXXXX.Models.UserInfo newUserEntry = new Models.UserInfo 
       { 
        SAMAccountName = p, 
        First_Name = searchResult.Properties.Contains("givenName") ? searchResult.Properties["givenName"][0].ToString() : string.Empty, 
        Last_Name = searchResult.Properties.Contains("sn") ? searchResult.Properties["sn"][0].ToString() : string.Empty, 
        Title = searchResult.Properties.Contains("title") ? searchResult.Properties["title"][0].ToString() : string.Empty, 
        Office = searchResult.Properties.Contains("l") ? searchResult.Properties["l"][0].ToString() : string.Empty, 
        Country = searchResult.Properties.Contains("c") ? searchResult.Properties["c"][0].ToString() : string.Empty, 
        Telephone = searchResult.Properties.Contains("telephoneNumber") ? searchResult.Properties["telephoneNumber"][0].ToString() : string.Empty, 
        Mobile_Phone = searchResult.Properties.Contains("mobile") ? searchResult.Properties["mobile"][0].ToString() : string.Empty, 
        Email_Address = searchResult.Properties.Contains("mail") ? searchResult.Properties["mail"][0].ToString() : string.Empty, 
        Image_Path = string.Format(Properties.Settings.Default.UserPicturePath, p), 
        LastUpdate = DateTime.Now, 
       }; 

更新

採取通知,我也是在這個提取查詢不同的數據庫,忽略所有的Linq的語句。 DirectoryEntry,DirectorySearcherSearchResult班級應該幫助你滿足你的需求。

更新2 變量p可以通過HttpContext.Current.User.Identity物業進行更換

更新3 這裏是LDAP名稱的最新列表(在那裏你看到searchResult.Properties.Contains( 「」)Over here它指向活動目錄中的不同用戶屬性

+0

問題是'HttpContext.Cu rrent.User.Identity'爲空,IsAuthenticated爲false,所以我沒有用戶名,即使我在AD帳戶上。 – Echilon

+0

這很奇怪。您是否已將web.config中的標記設置爲LDAP連接?因爲,如果是的話,你可以登錄,HttpContext.Current.User。身份不能爲空 – Eon

+0

<會員defaultProvider = 「ADMembershipProvider」> <添加名稱= 「ADMembershipProvider」 TYPE =「System.Web.Security.ActiveDirectoryMembershipProvider,System.Web程序,版本= 2.0.0.0,文化=中性公鑰= b03f5f7f11d50a3a」的connectionStringName = 「ADConnectionString」 connectionUsername = 「東西」 connectionPassword = 「東西」 attributeMapUsername = 「sAMAccountName賦」 enableSearchMethods = 「真」 attributeMapEmail = 「郵件」/> Eon

1

如果您正在使用與Active Directory窗體身份驗證嘗試此//代碼段

sub Page_Load(sender as object, e as EventArgs) 
    lblName.Text = "Hello " + Context.User.Identity.Name & "." 
    lblAuthType.Text = "You were authenticated using " & Context.User.Identity.AuthenticationType & "." 
end sub 

價:
Active Directory Authentication from ASP .NET
How to authenticate against the Active Directory by using forms authentication and Visual Basic .NET Building Secure ASP.NET Applications: Authentication, Authorization, and Secure Communication

編號: 您可以通過多種方式與ASP.NET使用Windows身份驗證:

  • Windows身份驗證不帶模擬。這是默認設置。 ASP.NET執行操作和使用應用程序的進程標識,默認情況下是Windows Server 2003

  • Windows身份驗證與模擬上的網絡服務帳戶訪問資源。採用這種方法,您可以模擬經過身份驗證的用戶並使用該身份執行操作和訪問資源。

  • 帶有固定身份假冒的Windows身份驗證。通過這種方法,您可以模擬一個固定的Windows帳戶以使用特定的身份訪問資源。在Windows Server 2003上,您應該避免使用這種模擬方法;而是使用具有自定義服務標識的自定義應用程序池。

根據文檔,您可以獲得經過身份驗證的用戶的Windows令牌。

IIdentity WinId= HttpContext.Current.User.Identity; 
WindowsIdentity wi = (WindowsIdentity)WinId; 

如果有什麼錯誤,然後檢查你的應用程序 模擬方法爲每How To: Use Windows Authentication in ASP.NET 2.0

的MSDN文檔,請參閱ScottGu的文章Recipe: Enabling Windows Authentication within an Intranet ASP.NET Web application

+0

注意:表單身份驗證正在使用時不適用。我已經在ASP.NET MVC中使用了它,而System.Web.HttpContext.Current.User將是一個System.Web.Security.FormsIdentity對象。 –

相關問題