我想创建一个应用程序来编辑服务器上的用户帐户。
服务器不只使用 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);
}
每当我尝试此操作时,我都会收到一个异常,即用户和/或密码未授权,与我使用的用户无关。管理员是内置的管理员用户帐户。
PrincipalContext
仅适用于 AD 还是也适用于本地帐户?我的代码有什么问题吗?
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);
}
}
}
上面的公共布尔值 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);
其他参考链接堆栈溢出帖子ContextType.Machine