与OAUTH的春天休息模板

时间:2011-11-01 18:31:23

标签: spring spring-mvc spring-security

我的控制器层用spring oauth2包裹。我正在编写集成测试来测试对控制器的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"

这将返回一个访问令牌,我用它来调用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进行经过身份验证的来电?

2 个答案:

答案 0 :(得分:11)

我在标题中设置了错误的参数..它应该是

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

答案 1 :(得分:1)

对于oauth2 API,这对我有用。

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

空格字符很重要。