在C#中,如何在网络机器上对用户进行身份验证?例如,我想在机器EXAMPLEMACHINE
上使用密码testpassword
对用户testuser
进行身份验证,该密码来自网络连接到EXAMPLEMACHINE
的另一台机器。例如,我在MYMACHINE
上,并且我想用EXAMPLEMACHINE
上的testpassword
对testuser
进行身份验证。
我尝试了以下操作,但它一直告诉我,LDAP服务器不可用:
PrincipalContext context =
new PrincipalContext(ContextType.Domain, exampleMachineDomain);
return context.ValidateCredentials(username, password);
如果您不使用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.....
}
如果您的机器不在域中,则需要使用ContextType.Machine
:
PrincipalContext context =
new PrincipalContext(ContextType.Machine, exampleMachineDomain);
return context.ValidateCredentials(username, password);
实现这一点的最佳方法是使用WNetUseConnection,这是一个Win32 API,它允许最直接的方式。实际上,你正试图呼叫
net use \server password /user:myUserName
,
这就是API的意图
这个问题已经回答了一个很好的例子。
由于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;
}
这个答案中提供了一些不同的选项。不过,粘贴在上方的片段应该可以工作。