Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 335
harshit Avatar asked Nov 01 '11 18:11

harshit


2 Answers

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

headers.set("Authorization","Bearer "+accessToken);
like image 75
harshit Avatar answered Sep 22 '22 17:09

harshit


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 .

like image 42
Rajaneesh Avatar answered Sep 23 '22 17:09

Rajaneesh