与OAUTH的春天休息模板

har*_*hit 6 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"
Run Code Online (Sandbox Code Playgroud)

这将返回一个访问令牌,我用它来调用api:

curl -v -H "Authorization: Bearer Access toekn value" "http://localhost:8080/profile/1.json"
Run Code Online (Sandbox Code Playgroud)

在使用时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));
Run Code Online (Sandbox Code Playgroud)

但是,我收到此错误:

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)
Run Code Online (Sandbox Code Playgroud)

我们如何使用经过身份验证的呼叫RestTemplate

har*_*hit 11

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

headers.set("Authorization","Bearer "+accessToken);
Run Code Online (Sandbox Code Playgroud)