Найдите приведенный ниже код, который можно использовать для тестирования.
Код в основном вызывает конечную точку OID C token для получения токена доступа.
Предполагается, что есть пользователь по имени tester1 , который может войти только с паролем.
Дополнительно для клиента требуется пароль. Но клиент также может быть настроен для работы без пароля.
// data for token request
MultiValueMap<String, String> params = new LinkedMultiValueMap<>();
params.add("grant_type", "password");
params.add("client_id", "yourclient");
params.add("username", "tester1");
params.add("password", "secret");
// construct token request (including authorization for client(
RequestEntity<MultiValueMap<String, String>> authRequest = RequestEntity
.post(new URI("https://keycloak.domain.com/auth/realms/yourrealm/protocol/openid-connect/token"))
.contentType(MediaType.APPLICATION_FORM_URLENCODED)
.accept(MediaType.APPLICATION_JSON)
.header("Authorization", httpBasicAuthorization("yourclient", "secret-client-credential"))
.body(params);
// execute request and test for success
TestRestTemplate restTemplate = new TestRestTemplate();
ResponseEntity<String> response = restTemplate.exchange(authRequest, String.class);
assertEquals(HttpStatus.OK, response.getStatusCode());
assertTrue(response.getHeaders().getContentType().isCompatibleWith(MediaType.APPLICATION_JSON));
// extract access token (JWT) from response
JacksonJsonParser jsonParser = new JacksonJsonParser();
final String accessToken = jsonParser.parseMap(response.getBody()).get("access_token").toString();