2011-11-01 93 views
5

我的控制器层用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验证的电话?

+0

那么,你是否将“accessToken”与每个REQUEST传递给服务器。因此,我认为您的REST API是无状态的,并且您每次都通过发送accessToken来保持其状态无状态。这是一个安全的解决方案?你是否在生产环境中使用它? – jsf

回答

9

我设置在头参数错误。应该

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

如何从请求中获取访问令牌?你的acessTOken字段在哪里设置? – user3629892

1

这是为我工作,为的oauth2 API。

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

设置授权时重要的空格字符。