【问题标题】:Get GUID or Native GUID from Active Directory从 Active Directory 获取 GUID 或本机 GUID
【发布时间】:2023-06-08 01:11:01
【问题描述】:

我正在编写一个 Web 服务来检查用户是否存在于 Active Directory 中以及用户帐户是否已启用。一旦它检查到,我就会继续验证他们的用户帐户。一旦他们成功输入用户名和密码,我想为我正在验证的人获取GUIDNativeGuid。我想使用GUIDNativeGUID 在 SQL Server 数据库中建立关系。

这是我正在采取的方法:

public string isAuthenticated (string serverName, string userName, string pwd)
{
    string _serverName, _userName, _pwd;
    _serverName = serverName;
    _userName = userName;
    _pwd = pwd;

    string message;

    if (DoesUserExist (_userName) == true)
    {
        if (isActive(userName) == true)
        {
            try
            {
                DirectoryEntry entry = new DirectoryEntry(_serverName, _userName, _pwd);
                object nativeObject = entry.NativeObject;
                //issue is here
                string GUID = entry.Guid.ToString();
                string GUIDID = entry.NativeGuid;
                //end of issue
                message = "Successfully authenticated";
            }
            catch(DirectoryServicesCOMException ex)
            {
                    message = ex.Message;
            }
        }
        else
        {
                message = "Account is disabled";
        }
    }
    else
    {
        message = "There's an issue with your account.";
    }
    return message;      
}

当我尝试获取 GUIDNativeGUID 时,它每次都会为不同的用户返回相同的 ID

我可以采取其他方法为 Active Directory 中的不同对象获取 UNIQUE ID 吗?

谢谢

【问题讨论】:

    标签: c# web-services active-directory directoryservices


    【解决方案1】:

    如果您使用的是 .NET 3.5 及更高版本,则应查看 System.DirectoryServices.AccountManagement (S.DS.AM) 命名空间。在此处阅读所有相关信息:

    基本上,您可以定义域上下文并在 AD 中轻松找到用户和/或组:

    // set up domain context
    using (PrincipalContext ctx = new PrincipalContext(ContextType.Domain))
    {
        // find a user
        UserPrincipal user = UserPrincipal.FindByIdentity(ctx, _userName);
    
        if(user != null)
        {
           // get the GUID
           var objectGuid = user.Guid;
        }
    }
    

    新的 S.DS.AM 让在 AD 中与用户和组一起玩变得非常容易!我现在没有要测试的广告 - 但我希望这确实会给你用户对象的 objectGuid 属性值。

    【讨论】:

    • 是的,这个可以。想粘贴几乎相同的代码。 UPV