Asp.net

從 asp.net 獲取經過身份驗證的 AD 使用者 objectGuid

  • January 25, 2013

我在 ASP.NET 應用程序中使用 Windows 身份驗證。我想知道如何最好地從目前登錄的使用者那裡獲取 objectGuid?

問候,埃吉爾。

您可以使用 System.DirectoryServices 命名空間來執行此操作。

Dim entry As DirectoryServices.DirectoryEntry
Dim mySearcher As System.DirectoryServices.DirectorySearcher
Dim result As System.DirectoryServices.SearchResult
Dim myEntry As DirectoryEntry
Dim domainName As String
Dim userId As String
Dim objectGuid As Guid

'Split the username into domain and userid parts
domainName = Page.User.Identity.Name.Substring(0, Page.User.Identity.Name.IndexOf("\"))
userId = Page.User.Identity.Name.Substring(Page.User.Identity.Name.IndexOf("\") + 1)

'Start at the top level domain
entry = New DirectoryEntry(domainName)

mySearcher = New DirectorySearcher(entry)

'Build a filter for just the user
mySearcher.Filter = ("(&(anr=" & userId & ")(objectClass=user))")

'Get the search result ...
result = mySearcher.FindOne

'... and then get the AD entry that goes with it
myEntry = result.GetDirectoryEntry

'The Guid property is the objectGuid
objectGuid = myEntry.Guid

可能有更好的方法來做到這一點,但這有效!

建議的解決方案相當昂貴。與其通過域和使用者名進行搜尋,更好的解決方案是使用 SID 來查找帳戶:

// using System.Security.Principal;
IPrincipal userPrincipal = HttpContext.Current.User;
WindowsIdentity windowsId = userPrincipal.Identity as WindowsIdentity;
if (windowsId != null)
{
   SecurityIdentifier sid = windowsId.User;

   using(DirectoryEntry userDe = new DirectoryEntry("LDAP://<SID=" + sid.Value + ">"))
   {
       Guid objectGuid = new Guid(userDe.NativeGuid);
   }
}

引用自:https://stackoverflow.com/questions/315403