如何使用rest-assured从keydepot服务获取承载令牌

w51jfk4q  于 2021-07-06  发布在  Java
关注(0)|答案(1)|浏览(396)

我正在试图找到正确的格式来获得一个载体令牌使用密钥斗篷。
使用 Postman ,我可以获得令牌没有问题。如果我点击 code 以及 Java - 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;

    }

很明显我错在哪里了吗?我应该将键/值传递到 .body() ?

g9icjywg

g9icjywg1#

您正在混合使用客户机id/secret,还使用basic auth。也 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)

相关问题