我想创建一个用于在服务器上编辑用户帐户的应用程序。
服务器不使用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还是本地帐户?我的代码有什么问题吗?
答案 0 :(得分: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
}
更改您的代码并将其包装在 usin g语句中,否则在尝试调用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()方法应该适用于你正在寻找的东西。
Have a look at 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