2016-11-14 141 views
0

我有這樣的代碼,用於捕獲用戶憑據: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 域/用戶 密碼

有什麼想法?

回答

0

問題是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