1

Im trying to get the url with basic authentication. I set the user/password as given below. The same credential is working in postman.

String RELATIVE_IDENTITY_URL  = "http://my_url/api/core/v3/people/email/abc@example.com";
    RestTemplate restTemplate;
    Credentials credentials;

    //1. Set credentials
    credentials = new UsernamePasswordCredentials("admin", "admin");

    CredentialsProvider credsProvider = new BasicCredentialsProvider();
    credsProvider.setCredentials( AuthScope.ANY, credentials);

    //2. Bind credentialsProvider to httpClient
    HttpClientBuilder httpClientBuilder = HttpClientBuilder.create();
    httpClientBuilder.setDefaultCredentialsProvider(credsProvider);
    CloseableHttpClient httpClient = httpClientBuilder.build();

    HttpComponentsClientHttpRequestFactory factory = new  
            HttpComponentsClientHttpRequestFactory(httpClient);

    //3. create restTemplate
    restTemplate = new RestTemplate();
    restTemplate.setRequestFactory(factory);

    //4. restTemplate execute
    String url = RELATIVE_IDENTITY_URL;

    String xml = restTemplate.getForObject(url,String.class); 
    System.out.println("Done");

I think the credentials are not set correctly. What is wrong here.? Error:

Exception in thread "main" org.springframework.web.client.HttpClientErrorException: 401 Unauthorized
    at org.springframework.web.client.DefaultResponseErrorHandler.handleError(DefaultResponseErrorHandler.java:91)
    at org.springframework.web.client.RestTemplate.handleResponse(RestTemplate.java:667)
    at org.springframework.web.client.RestTemplate.doExecute(RestTemplate.java:620)
    at org.springframework.web.client.RestTemplate.execute(RestTemplate.java:580)
    at org.springframework.web.client.RestTemplate.getForObject(RestTemplate.java:287)
    at com.src.AuthRestService.main(AuthRestService.java:85)    
Halcyon
  • 57,230
  • 10
  • 89
  • 128
Nidheesh
  • 4,390
  • 29
  • 87
  • 150
  • 1
    When you make the request how do you attach the credentials and are you setting the auth header? – Mike Tung May 31 '17 at 12:53
  • @MikeTung: I just missed to add that. I really thought it would be taking from the Set credentials part above. its working when I set it via headers. Thanks much – Nidheesh May 31 '17 at 13:11

1 Answers1

5

You are missing the auth header and setting the credentials in your rest template execution.

Mike Tung
  • 4,735
  • 1
  • 17
  • 24