java - 总是收到无效的 grant_type 参数或参数丢失,但适用于 postman

标签 java spring-boot keycloak

我正在尝试通过发布请求获取我的访问 token 。 我已经尝试过 postman 的请求,效果非常好。 但是当从我的应用程序尝试时,我收到错误

{error: "invalid_request", error_description: "Invalid grant_type parameter or parameter missing"}

这是我尝试过的java代码:

    RestAssured.baseURI 
    ="http://localhost:8180/auth/realms/acme/protocol/openid- 
    connect/token";
    RequestSpecification request = RestAssured.given();

    JSONObject requestParams = new JSONObject();
    requestParams.put("grant_type", "password");
    requestParams.put("username", "amineamine"); // Cast
    requestParams.put("password", "amineamine");
    requestParams.put("client_id", "app-backend-springboot");
    requestParams.put("client_secret",  "9a1707db-431d-437c-bb70- 
    0e5f5d61dcb0");

    request.body(requestParams.toJSONString());
    request.header("Content-Type", "application/x-www-form-urlencoded; 
    charset=UTF-8");

    Response response = request.post();
    int statusCode = response.getStatusCode();
    System.out.println(response.print());
    System.out.println("The status code recieved: " + statusCode);
    System.out.println("Response body: " + 
    response.body().asString());

这些是导入的:

import io.restassured.RestAssured;
import io.restassured.response.Response;
import io.restassured.specification.RequestSpecification;
import org.json.simple.JSONObject;

in postman enter image description here

最佳答案

我发现您的代码存在一个重大问题,我认为它可以很好地解释您的问题。您正在发送 JSON,但您正在发送一个 Content-Type header ,表明您正在发送表单数据。

由于您的 postman 示例正在发送表单数据,因此我认为这就是您想要做的。保留 Content-Type header 不变,但将 POST 正文更改为表单数据。按照你的方式,两者不匹配。表单数据的正确结构不是 JSON。

这里有一篇关于如何使用 RestAssured 发送表单数据的现有帖子:

How to send a Content-Type form-data request using rest assured?

总而言之,您希望将参数放入 Map 中,然后将该映射传递给请求构建器链中的 formParams() 方法。

关于java - 总是收到无效的 grant_type 参数或参数丢失,但适用于 postman ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55560426/

相关文章:

java - 识别输入流中的第一个字母

java - 尝试导入项目时,IntelliJ IDE 中未检测到框架

java - Spring Security 表单登录

java - 分段阅读_第 403 章

keycloak - Keycloak 的 OAuth2/OpenID Connect 端点是什么?

java - 边界填充(洪水填充)算法构建交互式 map 。 java

java - 我想在 catch block 运行时打印无效输入,但它没有发生。请帮助我

带有 Postgres 10.21 的 Keycloak 18.0

java - 为什么这个无限循环会收敛?

java - 将数据库调用放在自定义 ConstraintValidator 的 `isvalid()` 方法中会导致 stackoverflow 错误,因为它被重复调用