0

我想创建一个应用程序来编辑服务器上的用户帐户。

服务器不使用仅 AD 本地帐户。

我使用以下代码连接远程服务器:

try
{
    PrincipalContext oPrincipalContext = new PrincipalContext(ContextType.Machine, "192.168.123.110", null, ContextOptions.Negotiate, "Administrator", "password");
    try
    {
        MessageBox.Show(oPrincipalContext.ConnectedServer);
        GroupPrincipal oGroupPrincipal = GroupPrincipal.FindByIdentity(oPrincipalContext, "Goetter");
        try
        {
            // perform operations here
        }
        finally
        {
            oGroupPrincipal.Dispose();
        }
    }
    finally
    {
        oPrincipalContext.Dispose();
    }
}
catch (Exception ex)
{
    MessageBox.Show(ex.Message);
}

每当我尝试这个时,我都会得到一个异常,即用户和/或密码未经授权,与我使用的用户无关。Administrator 是内置的 Admin 用户帐户。

PrincipalContext仅适用于 AD 还是也适用于本地帐户?我的代码有什么问题吗?

4

1 回答 1

0
using(PrincipalContext oPrincipalContext = new PrincipalContext(ContextType.Machine, computer.Name, null, ContextOptions.Negotiate, Settings.UserName, Settings.UserPassword))
using(GroupPrincipal oGroupPrincipal = GroupPrincipal.FindByIdentity(oPrincipalContext, Settings.AdministratorsGroup))
{
    // perform operations here
}

更改您的代码并将其包装在using语句中,否则您在尝试调用 Dispose() 方法时可能会遇到一些错误,原因是您尝试处理连接时可能已经关闭。

如果您使用 ActiveDirectory,您可以在此处使用此代码并尝试任一示例

示例 1

如果您使用 .NET 3.5,则可以使用 System.DirectoryServices.AccountManagement 命名空间并轻松验证您的凭据:

// create a "principal context" - e.g. your domain (could be machine, too)
using(PrincipalContext pc = new PrincipalContext(ContextType.Domain, "YOURDOMAIN"))
{
    // validate the credentials
    bool isValid = pc.ValidateCredentials("myuser", "mypassword");
}

示例 2

using System.Security;
using System.DirectoryServices.AccountManagement;

public struct Credentials
{
    public string Username;
    public string Password;
}

public class Domain_Authentication
{
    public Credentials Credentials;
    public string Domain;

    public Domain_Authentication(string Username, string Password, string SDomain)
    {
        Credentials.Username = Username;
        Credentials.Password = Password;
        Domain = SDomain;
    }

    public bool IsValid()
    {
        using (PrincipalContext pc = new PrincipalContext(ContextType.Domain, Domain))
        {
            // validate the credentials
            return pc.ValidateCredentials(Credentials.Username, Credentials.Password);
        }
    }
}

上面的公共 bool IsValid() 方法应该适用于您要查找的内容。

看看 PrincipalContext.ValidateCredentials

对于您的 FindByIdentity 部分,您可以尝试以下替换代码

string strName = System.Security.Principal.WindowsIdentity.GetCurrent().Name; 
// This is here because of a .Net error that gets 0x80005000 on "isUser = user.IsMemberOf(groupU);"
string domainName = strName.Split('\\')[0]; 
var pc = new PrincipalContext(ContextType.Domain, domainName);

附加参考链接 StackOverFlow Post ContextType.Machine

于 2012-08-16T18:43:44.207 回答