我的目标是调用Web服务,这需要验证(当我在浏览器中浏览它的wsdl时,浏览器会要求我登录+密码)。
作为基础,我使用本教程中的示例。
现在我必须添加身份验证配置。
根据文档来配置WebServiceTemplate bean可能有所帮助。
但是使用Spring Boot,项目中没有applicationContext.xml或任何其他配置xml。
那么,如何使用Spring Boot配置WebServiceTemplate,或者还有什么可以解决这样的任务呢?
在Spring Boot中,您可以使用@Bean
批注配置bean。 您可以对不同的bean使用配置类。 在这些类中,您需要@Configuaration
注释。
本教程描述了Spring教程的“第二部分”。 提供教程的主要内容是:(基于Spring教程)
问题
我使用的SOAP Web服务需要基本的http身份验证,因此我需要在请求中添加身份验证标头。
没有身份验证
首先,您需要在没有身份验证的情况下实现请求,就像spring.io上的教程一样。 然后我将使用身份验证标头修改http请求。
在自定义WebServiceMessageSender中获取http请求
可以在WeatherConfiguration类中访问原始http连接。 在weatherClient中,您可以在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;
}
另一种方法是添加一个拦截器并在handleRequest()
方法中添加requestHeader, HttpUrlConnection
可以很容易地从TransportContextHolder
派生出HttpUrlConnection
;
这是拦截器类的代码:
public class SecurityInterceptor implements ClientInterceptor {
@Override
public boolean handleRequest(MessageContext messageContext) throws WebServiceClientException {
TransportContext context = TransportContextHolder.getTransportContext();
HttpUrlConnection connection = (HttpUrlConnection) context.getConnection();
try {
connection.addRequestHeader("Authorization","Basic VVNFUk5BTUU6cGFzc3dvcmQ=");
} catch (IOException e) {
log.error(e.getMessage());
}
return true;
}
//TODO:: other methods and constructor..
}
当然,将拦截器添加到WebTemplate:
WebServiceTemplate webServiceTemplate = new WebServiceTemplate(marshaller);
ClientInterceptor[] interceptors = new ClientInterceptor[]{new SecurityInterceptor()};
webServiceTemplate.setInterceptors(interceptors);
webServiceTemplate.marshalSendAndReceive(uriWebService, request)