我的控制器層用spring oauth2包裝。我正在編寫集成測試來測試控制器的api調用,所以我決定使用RestTemplate
。帶OAUTH的Spring Rest模板
以下是命令我通過捲曲使用:
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"
這將返回一個訪問令牌,我用它來撥打電話到API:
curl -v -H "Authorization: Bearer Access toekn value" "http://localhost:8080/profile/1.json"
在使用RestTemplate
,我能獲取訪問令牌,但現在我想通過此令牌來進行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));
但是,我得到這個錯誤:
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)
我們怎樣才能使使用RestTemplate
驗證的電話?
那麼,你是否將「accessToken」與每個REQUEST傳遞給服務器。因此,我認爲您的REST API是無狀態的,並且您每次都通過發送accessToken來保持其狀態無狀態。這是一個安全的解決方案?你是否在生產環境中使用它? – jsf