harshit
harshit

Reputation: 7951

Spring Rest Template with OAUTH

My controller layer is wrapped with spring oauth2. I am writing an integration test to test the api calls to controller, so I decided to use RestTemplate.

Following are commands I use via curl:

curl -v --cookie cookies.txt --cookie-jar cookies.txt  "http://localhost:8080/oauth/token?client_id=my-trusted-client&grant_type=password&scope=trust&username=xxxx&password=xxxxxx"

This returns an access token which I use to make the call to the api :

curl -v -H "Authorization: Bearer Access toekn value" "http://localhost:8080/profile/1.json"

While using RestTemplate, I was able to get the access token, but now I want to pass this token to make api calls:

DefaultHttpClient client = new DefaultHttpClient();
    HttpHeaders headers = new HttpHeaders();
    headers.set("Authorization: Bearer", accessToken);
    System.out.println(accessToken);
    HttpEntity<String> entity = new HttpEntity<String>(headers);
    System.out.println(restTemplate.exchange("http://localhost:8080/xxxx",HttpMethod.GET,entity,Object.class));

However, I get this error:

Exception in thread "main" org.springframework.web.client.HttpClientErrorException: 401 Unauthorized
at org.springframework.web.client.DefaultResponseErrorHandler.handleError(DefaultResponseErrorHandler.java:75)
at org.springframework.web.client.RestTemplate.handleResponseError(RestTemplate.java:486)
at org.springframework.web.client.RestTemplate.doExecute(RestTemplate.java:443)
at org.springframework.web.client.RestTemplate.execute(RestTemplate.java:401)
at org.springframework.web.client.RestTemplate.exchange(RestTemplate.java:377)
at com.gogii.service.SKUService.testGetAllSKU(SKUService.java:20)

How can we make authenticated calls using RestTemplate?

Upvotes: 6

Views: 21025

Answers (2)

Rajaneesh
Rajaneesh

Reputation: 181

This is working for me , for oauth2 API.

HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_JSON);
headers.set("Authorization","Bearer "+"ACCESS-TOKEN");

space characters important while setting Authorization .

Upvotes: 1

harshit
harshit

Reputation: 7951

I was setting wrong parameter in header.. it should be

headers.set("Authorization","Bearer "+accessToken);

Upvotes: 12

Related Questions