Skip to content

Commit f3af2c8

Browse files
committed
fix using admin auth with keycloak
1 parent 42f606d commit f3af2c8

3 files changed

Lines changed: 15 additions & 15 deletions

File tree

‎custom-token-auth-spi/pom.xml‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -6,7 +6,7 @@
66

77
<groupId>es.e-ucm.simva.keycloak</groupId>
88
<artifactId>custom-token-auth-spi</artifactId>
9-
<version>1.2.0</version>
9+
<version>1.3.0</version>
1010
<packaging>jar</packaging>
1111

1212
<name>Custom Token Auth SPI</name>

‎custom-token-auth-spi/src/main/java/es/eucm/utils/KeycloakOAuth2Client.java‎

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -19,6 +19,10 @@ public class KeycloakOAuth2Client {
1919
private String accessToken;
2020
private String refreshToken;
2121

22+
public String getAccessToken() {
23+
return this.accessToken;
24+
}
25+
2226
public KeycloakOAuth2Client() {
2327
this.objectMapper = new ObjectMapper();
2428
}

‎custom-token-auth-spi/src/main/java/es/eucm/utils/SimvaApiClient.java‎

Lines changed: 10 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -20,6 +20,7 @@
2020

2121
public class SimvaApiClient {
2222
private static final Logger logger = Logger.getLogger(SimvaApiClient.class);
23+
private static KeycloakOAuth2Client keycloakClient = new KeycloakOAuth2Client();
2324

2425
private static SimvaApiConfig apiConfig = new SimvaApiConfig();
2526
private String bearerToken;
@@ -38,20 +39,15 @@ public boolean isAuthentificated() {
3839
}
3940

4041
public void authenticate() throws IOException {
41-
// Create an ObjectMapper instance
42-
ObjectMapper objectMapper = new ObjectMapper();
43-
// Create a JSON object using ObjectNode
44-
ObjectNode payload = objectMapper.createObjectNode();
45-
payload.put("username", apiConfig.getAdminUsername());
46-
payload.put("password", apiConfig.getAdminPassword());
47-
// Convert the JSON object to a string
48-
String jsonPayload = objectMapper.writeValueAsString(payload);
49-
// Define the API URL
50-
String apiUrl = "/users/login";
51-
// Read the body of the response into a hashmap
52-
Map<String,Object> responseMap = this.sendPostRequest(apiUrl, jsonPayload);
53-
// Read the value of the "access_token" key from the hashmap
54-
this.bearerToken = "Bearer " + (String)responseMap.get("token");
42+
// Validate admin credentials to get a token
43+
boolean isValid = keycloakClient.validateUserCredentials(apiConfig.getAdminUsername(), apiConfig.getAdminPassword());
44+
if(!isValid) {
45+
throw new IOException("Invalid admin credentials for Simva API");
46+
} else {
47+
logger.info("Admin credentials validated");
48+
}
49+
// Store the bearer token for future requests
50+
this.bearerToken = "Bearer " + keycloakClient.getAccessToken();
5551
logger.info("Token: " + this.bearerToken);
5652
}
5753

0 commit comments

Comments
 (0)