在C#中,如何在网络计算机上验证用户?例如,我想要从与testuser
网络连接的其他计算机上,在计算机testpassword
上使用密码EXAMPLEMACHINE
对用户EXAMPLEMACHINE
进行身份验证。例如,我在MYMACHINE
,我想在testuser
上使用testpassword
对EXAMPLEMACHINE
进行身份验证。
我尝试过以下操作,但它一直告诉我, LDAP服务器不可用 :
PrincipalContext context =
new PrincipalContext(ContextType.Domain, exampleMachineDomain);
return context.ValidateCredentials(username, password);
答案 0 :(得分:2)
如果您的计算机不在域中,则需要使用ContextType.Machine
:
PrincipalContext context =
new PrincipalContext(ContextType.Machine, exampleMachineDomain);
return context.ValidateCredentials(username, password);
答案 1 :(得分:2)
如果您不使用Active Directory,则可以使用以下内容:
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);
}
}
}
如果您使用的是Active Directory,则可以使用以下内容:
PrincipalContext ctx = new PrincipalContext(ContextType.Domain);
// define a "query-by-example" principal - here, we search for a UserPrincipal
UserPrincipal qbeUser = new UserPrincipal(ctx);
// if you're looking for a particular user - you can limit the search by specifying
// e.g. a SAMAccountName, a first name - whatever criteria you are looking for
qbeUser.SamAccountName = "johndoe";
// create your principal searcher passing in the QBE principal
PrincipalSearcher srch = new PrincipalSearcher(qbeUser);
// find all matches
foreach(var found in srch.FindAll())
{
// do whatever here - "found" is of type "Principal" - it could be user, group, computer.....
}
答案 2 :(得分:1)
this answer中提供了一些不同的选项。但是,您在上方粘贴的代码段应工作。
答案 3 :(得分:1)
执行此操作的最佳方法是使用W32UseConnection,这是一种允许最直接方式的Win32 API。实际上,你正试着打电话
net use \\server password /user:myUserName
,
这个API的目的是什么。
this question回答了一个很好的例子。
因为PinvokeWindowsNetworking
函数在成功时返回null,所以最简单的验证码是
private static bool AuthenticateUserOnRemote(string server, string userName, string password)
{
var connected = PinvokeWindowsNetworking.connectToRemote(server, userName, password);
var disconnected = PinvokeWindowsNetworking.disconnectRemote(server);
return connected == null;
}