其他分享
首页 > 其他分享> > Spring Boot Web服务客户端身份验证

Spring Boot Web服务客户端身份验证

作者:互联网

我的目标是调用Web服务,这需要验证(当我在浏览器中浏览它的wsdl时,浏览器会询问我的登录密码).

作为基础,我使用this教程中的示例.

现在我必须添加身份验证配置.

根据documentation,配置WebServiceTemplate bean可能有所帮助.

但是使用Spring Boot,项目中没有applicationContext.xml或任何其他配置xml.

那么,如何使用Spring Boot配置WebServiceTemplate,或者还有什么可以解决这样的任务呢?

解决方法:

在Spring Boot中,您可以使用@Bean批注配置bean.您可以对不同的bean使用配置类.在这些类中,您需要@Configuaration注释.

这个tutorial描述了Spring教程的“第二部分”.提供教程的主要内容是:(基于Spring教程)

The problem

The SOAP webservice I consume requires basic http authentication, so I
need to add authentication header to the request.

Without authentication

First of all you need to have implemented a request without the
authentication like in the tutorial on the spring.io. Then I will
modify the http request with the authentication header.

Get the http request in custom WebServiceMessageSender

The raw http connection is accessible in the WeatherConfiguration
class. There in the weatherClient you can set the message sender in
the WebServiceTemplate. The message sender has access to the raw http
connection. So now it’s time to extend the
HttpUrlConnectionMessageSender and write custom implementation of it
that will add the authentication header to the request. My custom
sender is as follows:

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;
}

标签:spring,web-services,spring-boot-2,spring-ws
来源: https://codeday.me/bug/20190628/1312754.html