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

标签 java spring rest oauth oauth-2.0

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

以下 curl 命令成功运行,我得到了 token :

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"

以下获取 token 的测试也成功运行:

@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 从外部调用 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;
}

我得到的错误:

“缺少授权类型”

有什么可能出错的想法或任何其他方法吗?因为我完全坚持这一点。

谢谢

最佳答案

尝试这样做:

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

还有一件事,当您请求 token 时,请确保不要发送 json 请求,而是使用此 header :

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

关于java - Rest Api 调用使用 Spring Oauth2 给出错误 400,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40523255/

相关文章:

swing - JTable 行数限制

java - 从 Web 浏览器检测客户端 jre

java - QueryDSL NumberPath<BigDecimal> 大于从 MongoDB 集合提供不准确的结果

mysql - 如何在单独的文件中使用 DB 设置连接多个数据库(hsqldb、mysql)

java - RESTEasy 客户端。找不到内容类型应用程序/xml 的编写器

java - informix临时表的唯一ID是什么?

java - Playframework 2.5.3 ebean 包 com.avaje.ebean 不存在

java - 基于另一个 bean 的 Spring Conditional Bean 创建

java - Resteasy - 从 Javadoc 和注释生成 REST 文档

java - 不同 MIME 的多个 @GET - 如何使用普通的 HttpURLConnection() 来使用它