Rectangle 27 0

Reference Spring Boot's TestRestTemplate implementation as follows:

Especially, see the addAuthentication() method as follows:

private void addAuthentication(String username, String password) {
        if (username == null) {
            return;
        }
        List<ClientHttpRequestInterceptor> interceptors = Collections
                .<ClientHttpRequestInterceptor> singletonList(new BasicAuthorizationInterceptor(
                        username, password));
        setRequestFactory(new InterceptingClientHttpRequestFactory(getRequestFactory(),
                interceptors));
    }

Similarly, you can make your own RestTemplate easily by inheritance like TestRestTemplate.

java - Basic authentication for REST API using spring restTemplate - S...

java spring resttemplate jira-rest-api
Rectangle 27 0

Why not check the Spring 4 APIs to see which classes implement the required interface, namely ClientHttpRequestFactory?

As you'll see from the Javadoc, most likely you want HttpComponentsClientHttpRequestFactory, which uses the client from Apache's HttpComponents, the successor to the old commons HttpClient.

Yeah i see your point now and almost fine, my only issue now is that if i change the HttpClient to be import org.apache.http.client.HttpClient; and create it as final HttpClient client = new DefaultHttpClient(); i am not able to set the UsernamePasswordCredentials as there is no getState() on client. I know that probably stupid question but could you please recommend something as seeing this really first time. Cheers!

To be honest, I don't know off-hand. However you'll find lots of other questions and answers on here on HttpClient 4 and how to authenticate with it.

Oki, thanks! I get this working just fighting with 401 Unathorized, but i think i am on right track. Thanks again for your answer helped to find the right direction. Cheers.

java - Spring 4.0.0 basic authentication with RestTemplate - Stack Ove...

java spring apache resttemplate
Rectangle 27 0

I think this would be the most natural way of doing it, by filling in the header value and passing the header to the template.

Authorization
String plainCreds = "willie:p@ssword";
byte[] plainCredsBytes = plainCreds.getBytes();
byte[] base64CredsBytes = Base64.encodeBase64(plainCredsBytes);
String base64Creds = new String(base64CredsBytes);

HttpHeaders headers = new HttpHeaders();
headers.add("Authorization", "Basic " + base64Creds);

And this is to pass the header to the REST template (see this blog post):

HttpEntity<String> request = new HttpEntity<String>(headers);
ResponseEntity<Account> response = restTemplate.exchange(url, HttpMethod.GET, request, Account.class);
Account account = response.getBody();

Thanks - this worked for me. I had to point out that if you do not want to use the org.apache.commons.codec.binary.Base64 class and you would like to use the android Base64 class instead: import android.util.Base64;, you can replace the one line above with this: byte[] base64CredsBytes = Base64.encode(plainCredsBytes, Base64.DEFAULT);

java - Basic authentication for REST API using spring restTemplate - S...

java spring resttemplate jira-rest-api
Rectangle 27 0

with HttpClient 4.3 edits

Both Spring 3.0 and 3.1 and now 4.x have very good support for the Apache HTTP libraries:

CommonsClientHttpRequestFactory
HttpComponentsAsyncClientHttpRequestFactory

Lets start setting things up with HttpClient 4 and Spring 4.

RestTemplate
HttpContext
HttpComponentsClientHttpRequestFactory
createHttpContext
package org.soluvas.commons.util;

import java.net.URI;

import javax.annotation.Nullable;

import org.apache.http.HttpHost;
import org.apache.http.auth.AuthScope;
import org.apache.http.auth.UsernamePasswordCredentials;
import org.apache.http.client.AuthCache;
import org.apache.http.client.HttpClient;
import org.apache.http.client.protocol.HttpClientContext;
import org.apache.http.impl.auth.BasicScheme;
import org.apache.http.impl.client.BasicAuthCache;
import org.apache.http.impl.client.BasicCredentialsProvider;
import org.apache.http.protocol.HttpContext;
import org.springframework.http.HttpMethod;
import org.springframework.http.client.HttpComponentsClientHttpRequestFactory;
import org.springframework.web.client.RestTemplate;

/**
 * From http://www.baeldung.com/2012/04/16/how-to-use-resttemplate-with-basic-authentication-in-spring-3-1/
 * 
 * <p>And with that, everything is in place  the {@link RestTemplate} will now be able to support the Basic Authentication scheme; a simple usage pattern would be:
 * 
 * <pre>
 * final AuthHttpComponentsClientHttpRequestFactory requestFactory = new AuthHttpComponentsClientHttpRequestFactory(
 *                  httpClient, host, userName, password);
 * final RestTemplate restTemplate = new RestTemplate(requestFactory);
 * </pre>
 *   
 * And the request:
 *
 * <pre>
 * restTemplate.get("http://localhost:8080/spring-security-rest-template/api/foos/1", Foo.class);
 * </pre>
 * 
 * @author anton
 */
public class AuthHttpComponentsClientHttpRequestFactory extends
        HttpComponentsClientHttpRequestFactory {

    protected HttpHost host;
    @Nullable
    protected String userName;
    @Nullable
    protected String password;

    public AuthHttpComponentsClientHttpRequestFactory(HttpHost host) {
        this(host, null, null);
    }

    public AuthHttpComponentsClientHttpRequestFactory(HttpHost host, @Nullable String userName, @Nullable String password) {
        super();
        this.host = host;
        this.userName = userName;
        this.password = password;
    }

    public AuthHttpComponentsClientHttpRequestFactory(HttpClient httpClient, HttpHost host) {
        this(httpClient, host, null, null);
    }

    public AuthHttpComponentsClientHttpRequestFactory(HttpClient httpClient, HttpHost host, 
            @Nullable String userName, @Nullable String password) {
        super(httpClient);
        this.host = host;
        this.userName = userName;
        this.password = password;
    }

    @Override
    protected HttpContext createHttpContext(HttpMethod httpMethod, URI uri) {
       // Create AuthCache instance
        AuthCache authCache = new BasicAuthCache();
        // Generate BASIC scheme object and add it to the local auth cache
        BasicScheme basicAuth = new BasicScheme();
        authCache.put(host, basicAuth);

        // Add AuthCache to the execution context
        HttpClientContext localcontext = HttpClientContext.create();
        localcontext.setAuthCache(authCache);

        if (userName != null) {
            BasicCredentialsProvider credsProvider = new BasicCredentialsProvider();
            credsProvider.setCredentials(new AuthScope(host), new UsernamePasswordCredentials(userName, password));
            localcontext.setCredentialsProvider(credsProvider);
        }
        return localcontext;        
    }

}

It is here in the creation of the HttpContext that the basic authentication support is built in. As you can see, doing preemptive Basic Authentication with HttpClient 4.x is a bit of a burden: the authentication info is cached and the process of setting up this authentication cache is very manual and unintuitive.

And with that, everything is in place the RestTemplate will now be able to support the Basic Authentication scheme; a simple usage pattern would be:

final AuthHttpComponentsClientHttpRequestFactory requestFactory =
    new AuthHttpComponentsClientHttpRequestFactory(
                httpClient, host, userName, password);
final RestTemplate restTemplate = new RestTemplate(requestFactory);
restTemplate.get(
    "http://localhost:8080/spring-security-rest-template/api/foos/1",
    Foo.class);

For an in depth discussion on how to secure the REST Service itself, check out this article.

java - Spring 4.0.0 basic authentication with RestTemplate - Stack Ove...

java spring apache resttemplate