Jaffa
Jaffa

Reputation: 501

Http outbound channel adapter with basic authentication

I want to use Spring Boot and Integration DSL to send messages as HTTP Post to a rest service. Does anyone have an example of how to do this with (basic) authentication?

Everything else seems to be working fine. The log shows "org.springframework.web.client.HttpClientErrorException: 401 Unauthorized".

Upvotes: 2

Views: 856

Answers (1)

Artem Bilan
Artem Bilan

Reputation: 121552

Actually there is nothing to do with Basic Auth from the Spring Integration side.

This is a responsibility of ClientHttpRequestFactory.

For example I used to do something like this:

    @Bean
    public ClientHttpRequestFactory clientHttpRequestFactory(@Value("username") String username, 
                                                             @Value("password") String password) {
        HttpClient httpClient = HttpClientBuilder.create().
                setDefaultCredentialsProvider(getCredentialsProvider(username, password))
                .build();
        HttpComponentsClientHttpRequestFactory clientHttpRequestFactory =
                new HttpComponentsClientHttpRequestFactory(httpClient);
        return clientHttpRequestFactory;
    }

    private CredentialsProvider getCredentialsProvider(final String username, final String password) {
        CredentialsProvider cp = new BasicCredentialsProvider();
        cp.setCredentials(new AuthScope(AuthScope.ANY_HOST, AuthScope.ANY_PORT),
                new UsernamePasswordCredentials(username, password));
        return cp;
    }

And inject this clientHttpRequestFactory into the Http.outboundGateway().requestFactory().

All other ClientHttpRequestFactory may have another ways to configure Basic Auth for their requests objects.

Upvotes: 2

Related Questions