Http Basic Authentication not working with Spring WS and WebServiceTemplate credentials

不羁岁月 提交于 2019-12-10 20:37:43

问题


I try to add HTTP Basic Auth credentials to my SOAP-Request using Spring(-WS). The Request itself works, but no credentials are submitted. The HTTP header should look like:

[...]
Connection: Keep-Alive
User-Agent: Apache-HttpClient/4.1.1 (java 1.5)
Authorization: Basic mybase64encodedtopsecretcredentials=

But the last row is not missing. In MyConfig.java, I configure the Bean (no XML):

@Bean
public WebServiceTemplate webServiceTemplate() {
    WebServiceTemplate template = new WebServiceTemplate();
    try {
        template.setMarshaller(marshaller());  //Jaxb2Marshaller
        template.setUnmarshaller(marshaller());

        // proxy for tcpmon inspection
        template.setDefaultUri("http://127.0.0.1:29080/target/webservice.php");
        String username = environment.getProperty("config.username");
        String password = environment.getProperty("config.password");
        Credentials credentials = new UsernamePasswordCredentials(username, password);
        HttpComponentsMessageSender sender = new HttpComponentsMessageSender();
        sender.setCredentials(credentials);
        sender.afterPropertiesSet();
        template.setMessageSender(sender);
    } catch (Exception e) {
        // @todo: handle me
    }
    return template;
}

If you know the reason why the Authorization line is missing, please let me know. :) Thank you a lot in advance


回答1:


I had similar problem and this article helped me: https://looksok.wordpress.com/2014/09/06/spring-4-soap-request-with-http-basic-authentication/




回答2:


As described on this link (thank you @Milos), you need to create a class:

public class WebServiceMessageSenderWithAuth extends HttpUrlConnectionMessageSender{

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

        Base64.Encoder enc = Base64.getEncoder();
        String userpassword = "login:password"; // change to a real user and password
        String encodedAuthorization = enc.encodeToString(userpassword.getBytes());
        connection.setRequestProperty("Authorization", "Basic " + encodedAuthorization);

        super.prepareConnection(connection);
    }
}

And pass to message sender method:

setMessageSender(new WebServiceMessageSenderWithAuth());


来源:https://stackoverflow.com/questions/24779373/http-basic-authentication-not-working-with-spring-ws-and-webservicetemplate-cred

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!