7

我在 ASP.NET 应用程序中使用 Windows 身份验证。我想知道如何最好地从当前登录的用户那里获取 objectGuid?

问候,埃吉尔。

4

3 回答 3

12

建议的解决方案相当昂贵。与其通过域和用户名进行搜索,更好的解决方案是使用 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);
    }
}
于 2010-04-07T00:14:19.643 回答
4

您可以使用 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

可能有更好的方法来做到这一点,但这有效!

于 2008-11-25T08:47:38.227 回答
2

您需要使用NativeGuid属性。C#代码:

string login = HttpContext.Current.User.Identity.Name;
string domain = login.Substring(0, login.IndexOf('\\'));
string userName = login.Substring(login.IndexOf('\\') + 1);
DirectoryEntry domainEntry = new DirectoryEntry("LDAP://" + domain);
DirectorySearcher searcher = new DirectorySearcher(domainEntry);
searcher.Filter = string.Format(
   "(&(objectCategory=person)(objectClass=user)(sAMAccountName={0}))",
   userName);
SearchResult searchResult = searcher.FindOne();
DirectoryEntry entry = searchResult.GetDirectoryEntry();
Guid objectGuid = new Guid(entry.NativeGuid);
于 2009-05-06T05:54:11.640 回答