I achieved the ability to establish a personalized expiration time for each access token generated by utilizing a custom claim. Within the body, along with other credentials, I included the custom claim in the form-url-encoded format.
The claim retrieves the value from the request using the specified key. Inside the org.keycloak.representations.IDToken, there exists a function called exp(long) that essentially overrides the default expiration of the keycloak realm.
Before passing the time, it needs to be converted into Unix epoch format, which is the time format used by JWT (JSON Web Tokens) for storing time.
The following code represents the implementation within the setClaim function, which is utilized for creating a custom claim. If you are unfamiliar with the process of creating a custom claim, you can refer to this article for guidance .
@Override
protected void setClaim(IDToken token, ProtocolMapperModel mappingModel,
UserSessionModel userSession, KeycloakSession keycloakSession,
ClientSessionContext clientSessionCtx) {
int claimValue = 0;
// Get encoded value from request
String encodedClaimValue = keycloakSession.getContext().getHttpRequest().getDecodedFormParameters().getFirst("custom_exp");
if (encodedClaimValue != null) {
claimValue = Integer.parseInt(org.keycloak.common.util.Encode.decode(encodedClaimValue));
// Get the current local date and time
LocalDateTime currentTime = LocalDateTime.now();
// Add minutes to the current time
LocalDateTime futureTime = currentTime.plusMinutes(claimValue);
// Convert the future time to Unix epoch timestamp
long unixEpochTimestamp = futureTime.toEpochSecond(ZoneOffset.UTC);
// Override default Expiration
token.exp(unixEpochTimestamp);
}
}