繁体   English   中英

Rest Api调用使用Spring Oauth2给出错误400

[英]Rest Api call gives error 400 using Spring Oauth2

我正在使用Spring安全性Oauth2构建一个rest API来保护它。

以下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=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);
}

但是,当使用Spring RestTemplate从webapp外部调用其余端点时,会给出一个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;
}

我得到的错误:

“缺少补助金类型”

什么可能是错误的或任何其他方式的想法? 因为我完全坚持这个。

谢谢

尝试这样做:

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);

还有一件事,当您要求令牌时,请确保不发送json请求,但使用此标头:

headers.add("Content-Type", "application/x-www-form-urlencoded"); 

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM