Kerberos身份验证始终不成功

时间:2016-11-14 11:50:09

标签: c# .net active-directory

我有用于捕获用户凭据的代码:

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 域/用户 密码

有什么想法吗?

1 个答案:

答案 0 :(得分:1)

问题是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

相关问题