2015-10-07 141 views
1

我有以下代碼來向服務器發出POST請求。但是,Web服務器可以是Apache或IIS。客戶端資源發佈NTLM身份驗證失敗。適用於apache的基本身份驗證

Client client = new Client(new Context(), Protocol.HTTP); 
ClientResource resource = new ClientResource(url); 
resource.setRetryOnError(false); 
resource.setNext(client); 

resource.setChallengeResponse(ChallengeScheme.HTTP_BASIC,userName,pwd); 

response = resource.post(representation); 

下面的代碼適用於Apache的,但失敗了IIS,出現以下錯誤:

WARNING: Couldn't find any helper support the HTTP_NTLM challenge scheme. 
WARNING: Couldn't find any helper support the HTTP_Negotiate challenge scheme. 
Exception in thread "main" Unauthorized (401) - The request requires user authentication 

可能的原因是,Apache使用基本身份驗證和IIS使用NTML。第一次嘗試顯然是將IIS中的挑戰方案更改爲NTLM,如下所示,但得到相同的錯誤(我也已經爲restlet jar添加了網絡擴展)。

resource.setChallengeResponse(ChallengeScheme.HTTP_NTLM, userName, pwd); 

另外,我覺得有使用Apache HTTP客戶端(NTCredentials)班的方式,但我仍想使用的Restlet罐,避免了大量更改現有的代碼。

有什麼建議嗎?任何幫助,將不勝感激。 在此先感謝。

回答

1

Restlet中沒有對NTLM的內置支持。 Restlet Github存儲庫中的一個問題處理這樣的方面:https://github.com/restlet/restlet-framework-java/issues/467

我還看到了有關NTLM的Restlet文檔中的一個頁面:http://restlet.com/technical-resources/restlet-framework/guide/2.3/core/security/ntml-authentication。但它似乎有點過時,特別是對於HTTPClient部分。此外,HTTP客戶端擴展已棄用,並將在版本3中刪除。應改爲使用Jetty擴展。

也就是說,你可以嘗試使用Java本身提供的NTLM支持。爲此,您需要使用默認的Restlet HTTP客戶端,這是在類路徑中沒有提供客戶端連接器時使用的。下面是使用的一個樣本:

final String username = "username"; 
final String password = "password"; 
// Create your own authenticator 
Authenticator a = new Authenticator() { 
    public PasswordAuthentication getPasswordAuthentication() { 
     return (new PasswordAuthentication(
        username, password.toCharArray())); 
    } 
}; 
// Sets the default Authenticator 
Authenticator.setDefault(a); 

ClientResource cr = new ClientResource("http://..."); 
cr.post(...); 

此鏈接可以幫助你做到這一點:http://examples.javacodegeeks.com/core-java/net/authenticator/access-password-protected-url-with-authenticator/

希望它可以幫助你, 蒂埃裏

+0

結束了在IIS本身改變認證。啓用基本身份驗證(是的,我知道它不夠安全),以便與ChallengeScheme.HTTP_BASIC相同的代碼適用於Apache和IIS。 – Crusaderpyro