我的 Controller 层是用spring oauth2包装的。我正在编写一个集成测试来测试对 Controller 的api调用,因此我决定使用RestTemplate
。
以下是我通过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"
这将返回一个访问 token ,该 token 用于调用api:
curl -v -H "Authorization: Bearer Access toekn value" "http://localhost:8080/profile/1.json"
使用
RestTemplate
时,我可以获取访问 token ,但是现在我想传递此 token 进行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
进行经过身份验证的调用?
最佳答案
我在标题中设置了错误的参数。应该是
headers.set("Authorization","Bearer "+accessToken);
关于spring - OAUTH的Spring Rest模板,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7971119/