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;
        }

尽管凭证是正确的,但它总是抛出false作为不正确的凭证。控制台的输出如下所示:

Domain.net域/用户密码

任何想法吗?

问题是new System.Security.Principal.WindowsPrincipal(System.Security.Principal.WindowsIdentity.GetCurrent()).Identity.Name;以DOMAINusername格式返回用户名,而LdapConnection期望只看到用户名(您已经将域作为另一个参数发送)。

您可以使用Environment.UserName来获取用户名。

另一个问题是,ErrorCode你正在检查是不正确的。您将从DC获得"提供的凭据无效"消息(错误代码49)。

(顺便说一下,您不需要创建一个新的WindowsPrincipal,您可以直接使用System.Security.Principal.WindowsIdentity.GetCurrent().Name)

最新更新