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

2024-01-02

我的目标是调用需要身份验证的 Web 服务(当我在浏览器中打开其 wsdl 时,浏览器会要求我登录名+密码)。

作为基础,我使用来自this https://spring.io/guides/gs/consuming-web-service/教程。

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

根据文档 http://docs.spring.io/spring-ws/site/reference/html/client.html像配置 WebServiceTemplate bean 之类的东西可能会有所帮助。

但对于 Spring Boot,项目中没有 applicationContext.xml 或任何其他配置 xml。

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


在 Spring Boot 中,您可以使用以下方式配置您的 bean@Bean注解。您可以为不同的 bean 使用配置类。在这些课程中,您需要@Configuaration注解。

This tutorial https://looksok.wordpress.com/2014/09/06/spring-4-soap-request-with-http-basic-authentication/描述 Spring 教程的“第二部分”。提供的教程主要内容是:(基于Spring教程)

问题

我使用的 SOAP Web 服务需要基本的 http 身份验证,所以我 需要在请求中添加身份验证标头。

无需认证

首先,您需要在没有 身份验证就像 spring.io 上的教程一样。接着我会 使用身份验证标头修改 http 请求。

在自定义WebServiceMessageSender中获取http请求

原始 http 连接可在 WeatherConfiguration 中访问 班级。在weatherClient中你可以设置消息发送者 Web 服务模板。消息发送者可以访问原始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;
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

Spring Boot Web 服务客户端身份验证 的相关文章

随机推荐