Java 如何使用Rest-Assured从keydepose服务获取承载令牌
我正试图找到正确的格式,以获得一个载体令牌使用密钥斗篷 使用邮递员,我可以毫无疑问地获得代币。如果我点击Java 如何使用Rest-Assured从keydepose服务获取承载令牌,java,rest,keycloak,rest-assured,Java,Rest,Keycloak,Rest Assured,我正试图找到正确的格式,以获得一个载体令牌使用密钥斗篷 使用邮递员,我可以毫无疑问地获得代币。如果我点击code和Java-OkHttp 我得到这个片段: OkHttpClient client = new OkHttpClient().newBuilder() .build(); MediaType mediaType = MediaType.parse("application/x-www-form-urlencoded"); RequestBody body = R
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()
?您正在混合客户端id/secret并使用基本身份验证。此外,范围
似乎对客户端凭据流无效。因此,请尝试以下代码:
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)
只是一个友好的提醒:如果代码中的这些客户端机密是真实的,那么应该尽快停用这些客户端机密。现在,每个人都可以使用这些信息来验证您的密钥斗篷。@Sebu谢谢;我事先把他们都匿名了