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

标签 spring web-services spring-boot spring-ws

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

作为基础,我使用来自 this 的样本。教程。

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

根据 documentation像配置 WebServiceTemplate bean 之类的东西可能会有所帮助。

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

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

最佳答案

在 Spring Boot 中,您可以使用 @Bean 配置您的 bean。注解。您可以为不同的 bean 使用配置类。在这些类(class)中,您需要 @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 Boot Web 服务客户端身份验证,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35398045/

相关文章:

java - @MockBean 正确注入(inject)但在测试类上具有空值

java - Spring MVC - 当整数值为零时如何显示空白文本框

iphone - 从 iOS 应用程序向 RESTful Web 服务发送数据

android - 发送带有参数的 JSON 对象时出现 JSON 解析错误

intellij-idea - IntelliJ 2016.3.4 中突然出现 java.lang.NoClassDefFoundError

java - 按示例查询跳过原语?

java - createNativeQuery 中的分页

java - 什么是 java.lang.RuntimeException : org. apache.cxf.service.factory.ServiceConstructionException

java - Spring Boot休息 Controller : Return default Error JSON

string - 与 JSONB 相关的 PostgreSQL Hibernate-types 数据转换错误