簡體   English   中英

如何使用 Rest Assured 從 KeyCloak 服務獲取承載令牌

[英]How to get Bearer Token from KeyCloak Service using Rest Assured

我正在嘗試找到使用 Keycloak 獲取不記名令牌的正確格式。

使用 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;

    }

我哪里出錯了很明顯嗎? 我應該將鍵/值傳遞給.body()嗎?

您正在混合客戶端 ID/秘密並使用基本身份驗證。 此外, 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)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM