2011-11-01 15 views
5

Il mio controller è avvolto con una molla oauth2. Sto scrivendo un test di integrazione per testare le chiamate API al controller, quindi ho deciso di utilizzare RestTemplate.Spring Rest Template con OAUTH

Di seguito sono riportati i comandi che uso con ricciolo:

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" 

Ciò restituisce un token di accesso che io uso per effettuare la chiamata all'API:

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

Durante l'utilizzo RestTemplate, sono stato in grado di ottenere il token di accesso, ma ora voglio passare questo token per effettuare chiamate API:

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)); 

Tuttavia, ottengo questo errore:

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) 

Come possiamo effettuare chiamate autenticate utilizzando RestTemplate?

+0

Quindi, stai passando "accessToken" con ogni RICHIESTA al server. Quindi, presumo che la tua API REST sia stateless e tu mantenga il suo stato stateless inviando accessToken ogni volta. È una soluzione sicura? Lo stai usando in un ambiente di produzione? – jsf

risposta

9

mi stava tramontando parametro errato nell'intestazione .. dovrebbe essere

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

Come si ottiene il token di accesso dalla richiesta? Dove è ambientato il tuo campo acesstoken? – user3629892

1

Questo è il lavoro per me, per OAuth2 API.

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

spazio caratteri importanti durante l'impostazione Autorizzazione.

Problemi correlati