2016-02-14 161 views
2

我的目標是調用Web服務,這需要認證(當我在瀏覽器中瀏覽wsdl時,瀏覽器要求我登錄+密碼)。Spring Boot Web服務客戶端認證

作爲一個基地,我使用this教程中的示例。現在我不得不添加認證配置。

根據documentation的規定,類似配置WebServiceTemplate bean可能會有所幫助。

但是對於Spring Boot,項目中沒有applicationContext.xml或任何其他配置xml。

那麼,如何使用Spring Boot配置WebServiceTemplate,還有什麼可以解決這樣的任務?

+1

您可以隨時導入XML與'@ImportResource( 「applicationContext.xml中」)' – varren

回答

2

在Spring Boot中,您可以使用@Bean註釋來配置bean。您可以爲不同的bean使用配置類。在這些課程中,您需要@Configuaration註釋。

這個tutorial描述了Spring教程的「第二部分」。提供教程的主要事情是:(基於Spring教程)

問題

的SOAP Web服務我消耗需要基本的HTTP認證,所以我 需要認證頭添加到請求。

沒有認證

首先你需要在spring.io教程已經實現了一個請求,沒有 認證等等。然後我將 用認證頭修改http請求。

獲取自定義HTTP請求WebServiceMessageSender

原始的HTTP連接處於WeatherConfiguration 類訪問。在天氣客戶端中,您可以在 WebServiceTemplate中設置消息發送者。消息發件人可以訪問原始http 連接。因此,現在是擴展 HttpUrlConnectionMessageSender並編寫自定義實現 的時候了,它會將驗證頭添加到請求中。我的自定義 發件人如下:

public class WebServiceMessageSenderWithAuth extends HttpUrlConnectionMessageSender{ 

@Override 
protected void prepareConnection(HttpURLConnection connection) 
     throws IOException { 

    BASE64Encoder enc = new sun.misc.BASE64Encoder(); 
    String userpassword = "yourLogin:yourPassword"; 
    String encodedAuthorization = enc.encode(userpassword.getBytes()); 
    connection.setRequestProperty("Authorization", "Basic " + encodedAuthorization); 

    super.prepareConnection(connection); 
} 

@Bean 
public WeatherClient weatherClient(Jaxb2Marshaller marshaller){ 

WebServiceTemplate template = client.getWebServiceTemplate(); 
template.setMessageSender(new WebServiceMessageSenderWithAuth()); 

return client; 
}