I am working on keycloak authentication SPI in keycloak 15.0.1. I have used https://github.com/thomasdarimont/keycloak-extension-playground . I am working on creating two-way communication between ftl and java. I have faced an issue sending a response from Java to ftl. But ftl sends only a generated response. I want to alter the response and send it to the ftl. From ftl it gives a base64 encoded string to the action method. But the action method gives a generated response. How can I customize the response?
async function send_data_to_java() {
// Convert `dataUrl` to base64
let dataUrl = "Jisananam12289"; // Replace with actual data URL if needed
let base64DataUrl = btoa(dataUrl); // Encodes to base64 format
// Prepare face authentication data
let faceAuthData = { faceImage: base64DataUrl };
let loginActionUrl = document.getElementById("kc-u2f-login-form").action;
console.log("Face auth data:", faceAuthData);
// Convert faceAuthData to URL-encoded form data
let params = new URLSearchParams(faceAuthData).toString();
try {
// Send POST request with encoded data
let faceAuthResponse = await fetch(loginActionUrl, {
method: "post",
redirect: 'manual',
credentials: "include",
body: params,
headers: {
'Content-Type': 'application/x-www-form-urlencoded'
}
});
console.log("Response:", faceAuthResponse);
} catch (error) {
console.error("Error:", error);
}
}
This is the backend code in Java.
@Override
public void action(AuthenticationFlowContext context) {
MultivaluedMap<String, String> formParameters = context.getHttpRequest().getDecodedFormParameters();
String biometricImage = formParameters.getFirst("faceImage");
HttpURLConnection connection = null;
try {
// Setup connection
URL url = new URL(API_ENDPOINT);
connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("POST");
connection.setConnectTimeout(CONNECT_TIMEOUT);
connection.setReadTimeout(READ_TIMEOUT);
// Setup request headers
connection.setRequestProperty("Content-Type", "application/json");
connection.setDoOutput(true);
// Write request body
try (OutputStream outputStream = connection.getOutputStream()) {
String jsonRequest = "{\"type\":\"slap_left\"}";
outputStream.write(jsonRequest.getBytes("UTF-8"));
}
// Handle response
System.out.println("hello");
int responseCode = connection.getResponseCode();
System.out.println(responseCode);
String response = readResponse(connection);
log.info("Response Body: " + response);
String successResponse = "{\"status\":\"success\",\"message\":\"Authentication successful!\"}";
context.challenge(Response.status(200).entity(response).type(MediaType.APPLICATION_JSON).build());
context.success();
return;
} catch (Exception e) {
log.error("Error during fingerprint capture", e);
} finally {
if (connection != null) {
connection.disconnect();
}
}
}