From c5c1a8b1ad6b2333e3bd1b147e2d35e56b3712e0 Mon Sep 17 00:00:00 2001 From: Egor Cherniak Date: Thu, 2 Jun 2022 11:26:19 +0300 Subject: [PATCH] Fix keycloak response parsing (#10) * Fix keycloak response parsing * Fix checkstyle --- pom.xml | 6 ++++++ .../exception/BadResponseException.java | 16 ++++++++++++++ .../beholder/security/KeycloakService.java | 21 ++++++++++++++++++- 3 files changed, 42 insertions(+), 1 deletion(-) create mode 100644 src/main/java/dev/vality/beholder/exception/BadResponseException.java diff --git a/pom.xml b/pom.xml index d3fbc78..04c2449 100644 --- a/pom.xml +++ b/pom.xml @@ -127,6 +127,12 @@ org.springframework.boot spring-boot-starter-test test + + + com.vaadin.external.google + android-json + + org.testcontainers diff --git a/src/main/java/dev/vality/beholder/exception/BadResponseException.java b/src/main/java/dev/vality/beholder/exception/BadResponseException.java new file mode 100644 index 0000000..1cd03e1 --- /dev/null +++ b/src/main/java/dev/vality/beholder/exception/BadResponseException.java @@ -0,0 +1,16 @@ +package dev.vality.beholder.exception; + +public class BadResponseException extends RuntimeException { + + public BadResponseException(String message) { + super(message); + } + + public BadResponseException(Throwable throwable) { + super(throwable); + } + + public BadResponseException(String message, Throwable throwable) { + super(message, throwable); + } +} diff --git a/src/main/java/dev/vality/beholder/security/KeycloakService.java b/src/main/java/dev/vality/beholder/security/KeycloakService.java index 9c4c751..d90be4c 100644 --- a/src/main/java/dev/vality/beholder/security/KeycloakService.java +++ b/src/main/java/dev/vality/beholder/security/KeycloakService.java @@ -1,7 +1,11 @@ package dev.vality.beholder.security; import dev.vality.beholder.config.properties.KeycloakProperties; +import dev.vality.beholder.exception.BadFormatException; +import dev.vality.beholder.exception.BadResponseException; import lombok.RequiredArgsConstructor; +import org.json.JSONException; +import org.json.JSONObject; import org.keycloak.OAuth2Constants; import org.springframework.http.HttpEntity; import org.springframework.http.ResponseEntity; @@ -24,7 +28,22 @@ public class KeycloakService { .build(); ResponseEntity response = restTemplate.postForEntity(keycloakProperties.getUrl(), request, String.class); - return response.getBody(); + + if (!response.getStatusCode().is2xxSuccessful()) { + throw new BadResponseException( + String.format("Keycloak response: code: %s, body: %s", response.getStatusCode(), + response.getBody())); + } + return getAccessToken(response.getBody()); + } + + private String getAccessToken(String body) { + try { + JSONObject json = new JSONObject(body); + return json.getString("access_token"); + } catch (JSONException e) { + throw new BadFormatException(e); + } } }