Java RESTAPI调用使用SpringOAuth2时出现错误400
我正在使用SpringSecurityOAuth2构建一个RESTAPI来保护它 以下curl命令成功运行,我获得了令牌:Java RESTAPI调用使用SpringOAuth2时出现错误400,java,spring,rest,oauth,oauth-2.0,Java,Spring,Rest,Oauth,Oauth 2.0,我正在使用SpringSecurityOAuth2构建一个RESTAPI来保护它 以下curl命令成功运行,我获得了令牌: curl -X POST -vu clientapp:123456 http://localhost:8080/dms-application-0.0.1-SNAPSHOT/oauth/token -H "Accept: application/json" -d "password=spring&username=roy&grant_type=passwor
curl -X POST -vu clientapp:123456 http://localhost:8080/dms-application-0.0.1-SNAPSHOT/oauth/token -H "Accept: application/json" -d "password=spring&username=roy&grant_type=password&scope=read%20write&client_secret=123456&client_id=clientapp"
以下获取令牌的测试也成功运行:
@Test
public void getAccessToken() throws Exception {
String authorization = "Basic " + new String(Base64Utils.encode("clientapp:123456".getBytes()));
String contentType = MediaType.APPLICATION_JSON + ";charset=UTF-8";
// @formatter:off
String content = mvc
.perform(
post("/oauth/token")
.header("Authorization", authorization)
.contentType(
MediaType.APPLICATION_FORM_URLENCODED)
.param("username", "roy")
.param("password", "spring")
.param("grant_type", "password")
.param("scope", "read write")
.param("client_id", "clientapp")
.param("client_secret", "123456"))
.andExpect(status().isOk())
.andExpect(content().contentType(contentType))
.andExpect(jsonPath("$.access_token", is(notNullValue())))
.andExpect(jsonPath("$.token_type", is(equalTo("bearer"))))
.andExpect(jsonPath("$.refresh_token", is(notNullValue())))
.andExpect(jsonPath("$.expires_in", is(greaterThan(4000))))
.andExpect(jsonPath("$.scope", is(equalTo("read write"))))
.andReturn().getResponse().getContentAsString();
// @formatter:on
String token= content.substring(17, 53);
}
但是,当使用SpringRestTemplate从webapp外部调用rest端点时,会出现http错误400。
代码如下:
@RequestMapping(value = "/authentication", method = RequestMethod.POST, consumes = MediaType.APPLICATION_JSON_VALUE, produces = MediaType.APPLICATION_JSON_VALUE)
@ResponseBody
public ResponseEntity authenticate(@RequestBody CredentialsDto credentials) {
try {
String email = credentials.getEmail();
String password = credentials.getPassword();
String tokenUrl = "http://" + env.getProperty("server.host") + ":8080" + "/dms-application-0.0.1-SNAPSHOT" + "/oauth/token";
// create request body
JSONObject request = new JSONObject();
request.put("username", "roy");
request.put("password", "spring");
request.put("grant_type","password");
request.put("scope","read write");
request.put("client_secret","123456");
request.put("client_id","clientapp");
// set headers
HttpHeaders headers = new HttpHeaders();
String authorization = "Basic " + new String(Base64Utils.encode("clientapp:123456".getBytes()));
String contentType = MediaType.APPLICATION_FORM_URLENCODED.toString();
headers.set("Authorization",authorization);
headers.set("Accept","application/json");
headers.set("Content-Type",contentType);
HttpEntity<String> entity = new HttpEntity<String>(request.toString(), headers);
// send request and parse result
ResponseEntity<String> loginResponse = restClient.exchange(tokenUrl, HttpMethod.POST, entity, String.class);
// restClient.postForEntity(tokenUrl,entity,String.class,)
if (loginResponse.getStatusCode() == HttpStatus.OK) {
//JSONObject userJson = new JSONObject(loginResponse.getBody());
String response = loginResponse.getBody();
return ResponseEntity.ok(response);
} else if (loginResponse.getStatusCode() == HttpStatus.UNAUTHORIZED) {
// nono... bad credentials
return ResponseEntity.status(HttpStatus.UNAUTHORIZED).build();
}
} catch (Exception e) {
e.printStackTrace();
return new ResponseEntity(HttpStatus.INTERNAL_SERVER_ERROR);
}
return null;
}
@RequestMapping(value=“/authentication”,method=RequestMethod.POST,consumes=MediaType.APPLICATION\u JSON\u value,products=MediaType.APPLICATION\u JSON\u value)
@应答器
公共响应身份验证(@RequestBody-CredentialsDto-credentials){
试一试{
字符串email=credentials.getEmail();
字符串密码=凭据。getPassword();
字符串tokenUrl=“http://”+env.getProperty(“server.host”)+”:8080“+”/dms-application-0.0.1-SNAPSHOT“+”/oauth/token”;
//创建请求主体
JSONObject请求=新建JSONObject();
请求。输入(“用户名”、“罗伊”);
请求。输入(“密码”、“弹簧”);
请求。输入(“授权类型”、“密码”);
请求。提交(“范围”、“读写”);
请求。put(“客户机密”、“123456”);
请求。put(“客户id”、“客户PP”);
//设置标题
HttpHeaders=新的HttpHeaders();
stringauthorization=“Basic”+新字符串(Base64Utils.encode(“clientapp:123456.getBytes());
String contentType=MediaType.APPLICATION_FORM_URLENCODED.toString();
headers.set(“授权”,Authorization);
headers.set(“接受”、“应用程序/json”);
headers.set(“内容类型”,contentType);
HttpEntity=新的HttpEntity(request.toString(),headers);
//发送请求并解析结果
ResponseEntity loginResponse=restClient.exchange(tokenUrl、HttpMethod.POST、entity、String.class);
//postForEntity(令牌URL、实体、字符串、类)
if(loginResponse.getStatusCode()==HttpStatus.OK){
//JSONObject userJson=新的JSONObject(loginResponse.getBody());
字符串响应=loginResponse.getBody();
返回ResponseEntity.ok(响应);
}else if(loginResponse.getStatusCode()==HttpStatus.UNAUTHORIZED){
//不……不好的证件
返回ResponseEntity.status(HttpStatus.UNAUTHORIZED.build();
}
}捕获(例外e){
e、 printStackTrace();
返回新的响应属性(HttpStatus.INTERNAL_SERVER_ERROR);
}
返回null;
}
我得到的错误是:
“缺少授权类型”
有没有关于什么是错误的想法,或者有没有其他方法?因为我完全被这件事缠住了
谢谢试着这样做:
MultiValueMap<String, String> map = new LinkedMultiValueMap<String, String>();
map.add("username", "roy");
map.add("password", "spring");
map.add("grant_type", "password");
map.add("scope", "read write");
map.add("client_secret","123456");
map.add("client_id","clientapp");
HttpEntity request = new HttpEntity(map, headers);
尝试更改此
headers.set(“接受”、“应用程序/json”)
toheaders.setAccept(Arrays.asList(MediaType.APPLICATION_JSON))代码>。这是设置accept header400 response的正确方法,表示您在请求正文中发送的数据在语法上不正确。必须验证在请求正文中发送的json。您还可以在main方法中使用新的ObjectMapper().readValue('JSONDATA',Class.Class)测试它,以测试它是否正在反序列化
headers.add("Content-Type", "application/x-www-form-urlencoded");