Fix keycloak response parsing (#10)

* Fix keycloak response parsing

* Fix checkstyle
This commit is contained in:
Egor Cherniak 2022-06-02 11:26:19 +03:00 committed by GitHub
parent c4acb85ea0
commit c5c1a8b1ad
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
3 changed files with 42 additions and 1 deletions

View File

@ -127,6 +127,12 @@
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
<exclusions>
<exclusion>
<groupId>com.vaadin.external.google</groupId>
<artifactId>android-json</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>org.testcontainers</groupId>

View File

@ -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);
}
}

View File

@ -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<String> 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);
}
}
}