Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Basic Authentication with RestTemplate (3.1)

I am trying to reproduce the following curl command using Java:

curl -v -u user:pass http://myapp.com/api

This command returns some JSON data.

My buggy Java implementation is as follows:

@Test
public void callTest() {
    RestTemplate restTemplate = createRestTemplate("user", "pass");
    URI uri = new URI("http://myapp.com/api");
    String res = restTemplate.getForObject(uri, String.class);
}

private static RestTemplate createRestTemplate(String username, String password) {

    UsernamePasswordCredentials cred = new UsernamePasswordCredentials(username, password);
    BasicCredentialsProvider cp = new BasicCredentialsProvider();
    cp.setCredentials(AuthScope.ANY, cred);
    DefaultHttpClient client = new DefaultHttpClient();
    client.setCredentialsProvider(cp);
    ClientHttpRequestFactory factory = new HttpComponentsClientHttpRequestFactory(client);

    RestTemplate restTemplate = new RestTemplate(factory);
    // set the media types properly
    return restTemplate;
}

Yet, when I execute the test, it returns a org.springframework.web.client.HttpClientErrorException: 401 Unauthorized exception.

When logging in DEBUG, I see no information about the authentication...

What am I doing wrong while setting the authentication credentials?

like image 974
Jean Logeart Avatar asked Jan 17 '13 16:01

Jean Logeart


People also ask

How do you add basic authentication to RestTemplate?

Now that everything is in place, the RestTemplate will be able to support the Basic Authentication scheme just by adding a BasicAuthorizationInterceptor: restTemplate. getInterceptors(). add( new BasicAuthorizationInterceptor("username", "password"));

How do I pass the authorization token in RestTemplate?

Setting bearer token for a GET request RestTemplate restTemplate = new RestTemplate(); String customerAPIUrl = "http://localhost:9080/api/customer"; HttpHeaders headers = new HttpHeaders(); headers. set("Authorization", "Bearer " + accessToken); //accessToken can be the secret key you generate. headers.


1 Answers

Instantiating using

HttpClient client = new HttpClient();

doesn't exist anymore and class DefaultHttpClient is deprecated from HttpComponents HttpClient from version 4.3. So other answer are either invalid or deprecated. Here is my version, I wrote this class for rest requests which require basic authentication:

import org.apache.http.auth.AuthScope;
import org.apache.http.auth.UsernamePasswordCredentials;
import org.apache.http.client.CredentialsProvider;
import org.apache.http.client.HttpClient;
import org.apache.http.impl.client.BasicCredentialsProvider;
import org.apache.http.impl.client.HttpClients;
import org.springframework.http.client.HttpComponentsClientHttpRequestFactory;
import org.springframework.web.client.RestTemplate;

public class RestClient extends RestTemplate {
    public RestClient(String username, String password) {
        CredentialsProvider credsProvider = new BasicCredentialsProvider();
        credsProvider.setCredentials(
                new AuthScope(null, -1),
                new UsernamePasswordCredentials(username, password));
        HttpClient httpClient = HttpClients.custom().setDefaultCredentialsProvider(credsProvider).build();
        setRequestFactory(new HttpComponentsClientHttpRequestFactory(httpClient));
    }
}

Then use it like, for example:

RestClient restClient = new RestClient("username", "password");

String result = restClient.postForObject(...
like image 76
Utku Özdemir Avatar answered Sep 21 '22 00:09

Utku Özdemir