Kerberos身份验证总是不成功
问题描述:
我有这样的代码,用于捕获用户凭据:Kerberos身份验证总是不成功
string domain = Domain.GetComputerDomain().ToString();
Console.WriteLine(domain);
string username =
new System.Security.Principal.WindowsPrincipal(System.Security.Principal.WindowsIdentity.GetCurrent())
.Identity.Name;
Console.WriteLine(username);
Console.Write("Password: ");
//there are far better ways to get a hidden password this was just an easy way as it's irrelevant to the point of the application, will improve
string password = null;
while (true)
{
var key = Console.ReadKey(true);
if (key.Key == ConsoleKey.Enter)
break;
password += key.KeyChar;
}
而这种方法对于使用Kerberos身份验证:
private static bool ValidateCredentialsKerberos(string username, string password, string domain)
{
var credentials
= new NetworkCredential(username, password, domain);
var id = new LdapDirectoryIdentifier(domain);
using (var connection = new LdapConnection(id, credentials, AuthType.Kerberos))
{
connection.SessionOptions.Sealing = true;
connection.SessionOptions.Signing = true;
try
{
connection.Bind();
}
catch (LdapException lEx)
{
if (ERROR_LOGON_FAILURE == lEx.ErrorCode)
{
return false;
}
throw;
}
}
return true;
}
它总是抛出虚假的,尽管凭据是正确不正确的凭据。输出到控制台如下:
Domain.net 域/用户 密码
有什么想法?
答
问题是new System.Security.Principal.WindowsPrincipal(System.Security.Principal.WindowsIdentity.GetCurrent()).Identity.Name;
以DOMAIN \ username格式返回用户名,而LdapConnection希望只看到用户名(您已经将域名作为另一个参数发送)。
您可以使用Environment.UserName
来获取用户名。
另一个问题是您正在检查的ErrorCode
是不正确的。你会得到“提供的凭证是无效的。”来自DC的消息(错误代码49)。
(顺便说一句,你没有创建一个新的WindowsPrincipal
,你可以只用System.Security.Principal.WindowsIdentity.GetCurrent().Name
)