如何使用 Rest Assured 从 KeyCloak 服务获取 Bearer Token

How to get Bearer Token from KeyCloak Service using Rest Assured

我正在尝试找到使用 Keycloak 获取 Bearer Token 的正确格式。

使用 Postman,我可以毫无问题地获取令牌。如果我点击 codeJava - OkHttp 我得到这个片段:

OkHttpClient client = new OkHttpClient().newBuilder()
  .build();
MediaType mediaType = MediaType.parse("application/x-www-form-urlencoded");
RequestBody body = RequestBody.create(mediaType, "grant_type=client_credentials&client_id=amc-front-shop-service&client_secret=18hsudf9-0132-4r6d-804f-b134837d0d29");
Request request = new Request.Builder()
  .url("https://kc.services.enderby.com/auth/realms/FE-SHOP/protocol/openid-connect/token")
  .method("POST", body)
  .addHeader("Content-Type", "application/x-www-form-urlencoded")
  .build();
Response response = client.newCall(request).execute();

当我尝试在 Rest Assured 中对请求建模时,我收到 400 错误但不清楚原因:

 private static RequestSpecification keycloakServiceRequestSpec;
    private static String access_token;

    private void setKeycloakServiceSpecs() {
        keycloakServiceRequestSpec = new RequestSpecBuilder()
                .setContentType(ContentType.URLENC)
                .build();
    }

    @Test
    public String getAccessToken() {

        setKeycloakServiceSpecs();

        String clientId = "18hsudf9-0132-4r6d-804f-b134837d0d29";
        String clientSecret = "amc-front-shop-service";

        Response response =

        given()
                .auth().preemptive().basic(clientId, clientSecret)
                        .contentType("application/x-www-form-urlencoded")
                .formParam("grant_type", "client_credentials")
                .formParam("scope", "openid")
        .when()
                .post("https://kc.services.enderby.com/auth/realms/FE-SHOP/protocol/openid-connect/token").
         then().
                assertThat().statusCode(200).extract().response();

        String json = response.getBody().asString();
        JsonPath jsonPath = new JsonPath(json);

        access_token =  jsonPath.getString("access_token");

        logger.info("Oauth Token:" +  access_token);

        return access_token;

    }

我错在哪里很明显吗?我应该将 key/values 传递给 .body() 吗?

您正在混合客户端 id/secret 并且还使用基本身份验证。此外 scope 似乎对客户端凭据流无效。所以尝试代码:

        String clientSecret = "18hsudf9-0132-4r6d-804f-b134837d0d29";
        String clientId = "amc-front-shop-service";

        Response response =

        given()
                .auth().preemptive()
                .contentType("application/x-www-form-urlencoded")
                .formParam("grant_type", "client_credentials")
                .formParam("client_id", clientId)
                .formParam("client_secret", clientSecret)