Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -113,6 +113,7 @@ image:images/Create-authentication-execution.png[Adding an Authentication Execut

Authentication executions can optionally have a reference value configured. This can be utilized by the _Authentication Method Reference (AMR)_ protocol mapper to populate the _amr_ claim in OIDC access and ID tokens (for more information on the
AMR claim, see https://www.rfc-editor.org/rfc/rfc8176.html[RFC-8176]). When the _Authentication Method Reference (AMR)_ protocol mapper is configured for a client, it will populate the _amr_ claim with the reference value for any authenticator execution the user successfully completes during the authentication flow.
An execution can also have a *Max age* configured, in seconds. It applies when the user authenticates again in the same SSO session, for example through the SSO cookie: the reference value of an execution completed in an earlier authentication is only populated if that execution completed within the max age. The default of 0 means the reference value is only populated in the tokens of the authentication that completed the execution. The methods a token reports are fixed when the authentication completes, so refreshed tokens report the same _amr_ as the tokens issued at login.

.Adding an authenticator reference value
image:images/config-authenticator-reference.png[Configuring an Authenticator Reference Value]
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -3282,7 +3282,7 @@ referral=Referral
referralHelp=Specifies if LDAP referrals should be followed or ignored. Please note that enabling referrals can slow down authentication as it allows the LDAP server to decide which other LDAP servers to use. This could potentially include untrusted servers.
authenticatorRefConfig.value.help=Add a custom reference name for the authenticator. When this authenticator is successfully completed during an authentication flow, the Authentication Method Reference (AMR) protocol mapper will use this value to populate the amr claim of the generated tokens. Note, the AMR protocol must be configured for the given client to populate the AMR claim.
authenticatorRefConfig.value.label=Authenticator Reference
authenticatorRefConfig.maxAge.help=The max age in seconds that the authenticator reference value is good for in an SSO session. When the Authentication Method Reference (AMR) protocol mapper is used, the AMR will only be considered valid and populated in the token if the authenticator execution was completed within the specified max age.
authenticatorRefConfig.maxAge.help=The max age in seconds that the authenticator reference value is good for in an SSO session. An execution completed during the current authentication is always populated in the token by the Authentication Method Reference (AMR) protocol mapper. For later authentications in the same SSO session, such as a login through the SSO cookie, the reference is only populated if the execution was completed within the specified max age, evaluated when that later authentication completes. Defaults to 0, which means the reference is only populated in tokens of the authentication that completed the execution.
authenticatorRefConfig.maxAge.label=Authenticator Reference Max Age
loa-condition-level=Level of Authentication (LoA)
loa-condition-level.tooltip=Level of authentication. This value should be always integer, which is greater or equal to 0. The subflows in the authentication flow should be always ordered from lowest levels to a higher levels.
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -200,6 +200,19 @@ public final class Constants {
// Authentication session note containing a serialized map of successfully completed authentication executions and their associated times
public static final String AUTHENTICATORS_COMPLETED = "authenticators-completed";

// Authentication session auth note containing a serialized list of the authentication executions completed during the
// current authentication, as opposed to executions carried over from earlier authentications in the SSO session.
// Cleared with the other auth notes when the flow is reset.
public static final String AUTHENTICATORS_COMPLETED_CURRENT_AUTHENTICATION = "authenticators-completed-current-authentication";

// Client session note containing a serialized list of the authentication execution ids whose reference values the
// Authentication Method Reference (AMR) protocol mapper reports in every token of the client session. Resolved once, when
// an authentication attaches to the client session (AuthenticationProcessor.attachSession): executions completed by that
// authentication unconditionally, executions carried over from earlier authentications in the SSO session only while within
// their configured max age. Absent on client sessions no authentication attached to, such as those created by token exchange,
// and on client sessions attached before the note existed; the mapper then falls back to the user session's completed executions.
public static final String AMR_AUTHENTICATION_EXECUTIONS = "amr-authentication-executions";

// Authentication session (and user session) note, which contains map with authenticated levels and the times of their authentications,
// so it is possible to check when particular level expires and needs to be re-authenticated
public static final String LOA_MAP = "loa-map";
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -42,6 +42,7 @@
import org.keycloak.events.EventBuilder;
import org.keycloak.forms.login.LoginFormsProvider;
import org.keycloak.http.HttpRequest;
import org.keycloak.models.AuthenticatedClientSessionModel;
import org.keycloak.models.AuthenticationExecutionModel;
import org.keycloak.models.AuthenticationFlowModel;
import org.keycloak.models.AuthenticatorConfigModel;
Expand All @@ -60,6 +61,7 @@
import org.keycloak.protocol.LoginProtocol.Error;
import org.keycloak.protocol.RestartLoginCookie;
import org.keycloak.protocol.oidc.TokenManager;
import org.keycloak.protocol.oidc.utils.AmrUtils;
import org.keycloak.services.ErrorPage;
import org.keycloak.services.ErrorPageException;
import org.keycloak.services.ServicesLogger;
Expand Down Expand Up @@ -1229,6 +1231,12 @@ public static ClientSessionContext attachSession(AuthenticationSessionModel auth
clientSessionCtx.getClientSession().removeNote(FIRST_OFFLINE_ACCESS);
}

// Fix the executions the amr claim reports for this client session now, as the level of authentication is fixed
// just above. Every token of the client session, refreshed ones included, then reports the authentication that issued it.
AuthenticatedClientSessionModel clientSession = clientSessionCtx.getClientSession();
clientSession.setNote(Constants.AMR_AUTHENTICATION_EXECUTIONS,
AmrUtils.resolveAuthenticationExecutions(authSession, clientSession.getUserSession(), realm));
Comment thread
Copilot marked this conversation as resolved.
Resolved

event.user(user)
.detail(Details.USERNAME, username)
.session(userSession);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,9 @@
package org.keycloak.authentication.authenticators.util;

import java.io.IOException;
import java.util.LinkedHashSet;
import java.util.Map;
import java.util.Set;

import jakarta.ws.rs.core.MultivaluedMap;

Expand Down Expand Up @@ -125,19 +127,43 @@ public static Map<String, Integer> parseCompletedExecutions(String note){
public static void updateCompletedExecutions(AuthenticationSessionModel authSession, UserSessionModel userSession, String executionId){
Map<String, Integer> completedExecutions = parseCompletedExecutions(authSession.getUserSessionNotes().get(Constants.AUTHENTICATORS_COMPLETED));

// attempt to fetch previously completed authenticators
// attempt to fetch previously completed authenticators. An execution completed again in the current authentication keeps its new time.
if (userSession != null){
Map<String, Integer> prevCompleted = parseCompletedExecutions(userSession.getNote(Constants.AUTHENTICATORS_COMPLETED));
logger.debugf("merging completed executions from previous authentication session %s", prevCompleted);
completedExecutions.putAll(prevCompleted);
prevCompleted.forEach(completedExecutions::putIfAbsent);
}

// set new execution and serialize note
completedExecutions.put(executionId, Time.currentTime());

// the executions of the current authentication are tracked separately, so they can be told apart from carried over ones
// when the authentication attaches to a client session. An auth note, so a reset of the flow discards it with the execution statuses.
Set<String> currentAuthenticationExecutions = parseExecutionIds(authSession.getAuthNote(Constants.AUTHENTICATORS_COMPLETED_CURRENT_AUTHENTICATION));
currentAuthenticationExecutions.add(executionId);
try {
authSession.setUserSessionNote(Constants.AUTHENTICATORS_COMPLETED, JsonSerialization.writeValueAsString(completedExecutions));
authSession.setAuthNote(Constants.AUTHENTICATORS_COMPLETED_CURRENT_AUTHENTICATION, JsonSerialization.writeValueAsString(currentAuthenticationExecutions));
} catch (IOException e) {
throw new IllegalStateException(e);
}
}

/**
* Parse a serialized list of authentication execution ids, as stored in the
* {@link Constants#AUTHENTICATORS_COMPLETED_CURRENT_AUTHENTICATION} and {@link Constants#AMR_AUTHENTICATION_EXECUTIONS} notes.
*
* @param note The serialized list, or null when nothing has been recorded
* @return The execution ids in their recorded order. Never null.
*/
public static Set<String> parseExecutionIds(String note){
if (note == null){
return new LinkedHashSet<>();
}
try {
String updated = JsonSerialization.writeValueAsString(completedExecutions);
authSession.setUserSessionNote(Constants.AUTHENTICATORS_COMPLETED, updated);
return JsonSerialization.readValue(note, new TypeReference<LinkedHashSet<String>>() {});
} catch (IOException e) {
logger.warnf("Invalid format of the authentication execution ids list. Saved value was: %s", note);
throw new IllegalStateException(e);
}
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,7 @@
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;

import org.keycloak.OAuth2Constants;
import org.keycloak.authentication.authenticators.util.AuthenticatorUtils;
Expand Down Expand Up @@ -104,6 +105,17 @@ public static ProtocolMapperModel create(String name, boolean accessToken, boole
* @return The authenticator reference values associated with the completed executions
*/
protected List<String> getAmr(AuthenticatedClientSessionModel clientSession, RealmModel realmModel) {
String resolvedExecutions = clientSession.getNote(Constants.AMR_AUTHENTICATION_EXECUTIONS);
if (resolvedExecutions != null) {
Comment on lines +108 to +109
Set<String> executions = AuthenticatorUtils.parseExecutionIds(resolvedExecutions);
logger.debugf("found the following authentication executions resolved for the client session: %s", executions);
List<String> refs = AmrUtils.getAuthenticationExecutionReferences(executions, realmModel);
logger.debugf("amr %s set in token", refs);
return refs;
}

// No authentication attached to this client session since the executions were resolved on attach (token exchange,
// client sessions from before the note existed): report the user session's completed executions within their max age.
Map<String, Integer> executions = AuthenticatorUtils.parseCompletedExecutions(clientSession.getUserSession().getNote(Constants.AUTHENTICATORS_COMPLETED));
logger.debugf("found the following completed authentication executions: %s", executions.toString());
List<String> refs = AmrUtils.getAuthenticationExecutionReferences(executions, realmModel);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -17,13 +17,23 @@

package org.keycloak.protocol.oidc.utils;

import java.io.IOException;
import java.util.Collection;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;

import org.keycloak.authentication.authenticators.util.AuthenticatorUtils;
import org.keycloak.common.util.Time;
import org.keycloak.models.AuthenticationExecutionModel;
import org.keycloak.models.AuthenticatorConfigModel;
import org.keycloak.models.Constants;
import org.keycloak.models.RealmModel;
import org.keycloak.models.UserSessionModel;
import org.keycloak.sessions.AuthenticationSessionModel;
import org.keycloak.util.JsonSerialization;

import org.jboss.logging.Logger;

Expand All @@ -35,10 +45,107 @@ public class AmrUtils {
private static final Logger logger = Logger.getLogger(AmrUtils.class);

/**
* Get the configured authenticator reference values for the specified executions. If no
* Resolve the authentication executions whose reference values the amr claim reports for the client session an
* authentication is attaching to, in the same way the level of authentication is fixed on the client session at that
* point. An execution completed during the attaching authentication is always reported. An execution carried over from
* an earlier authentication in the SSO session is reported only while within its configured max age, evaluated now.
* Every token of the client session, refreshed ones included, then reports the same methods, as it reports the same
* auth_time.
*
* @param authSession The authentication session being attached
* @param userSession The user session the authentication attached to. Its completed executions already include the attaching authentication's own.
* @param realm The realm the executions are configured in
* @return The serialized list of execution ids, an empty list when the client session reports no method
*/
public static String resolveAuthenticationExecutions(AuthenticationSessionModel authSession, UserSessionModel userSession, RealmModel realm) {
Set<String> current = AuthenticatorUtils.parseExecutionIds(authSession.getAuthNote(Constants.AUTHENTICATORS_COMPLETED_CURRENT_AUTHENTICATION));
Map<String, Integer> completed = AuthenticatorUtils.parseCompletedExecutions(userSession.getNote(Constants.AUTHENTICATORS_COMPLETED));

Set<String> resolved = new LinkedHashSet<>(current);
completed.forEach((executionId, completedAt) -> {
if (resolved.contains(executionId)) {
return;
}
Map<String, String> config = getExecutionConfig(executionId, realm);
if (config != null && carriesOver(config, completedAt)) {
Comment on lines +64 to +70
resolved.add(executionId);
}
});
logger.debugf("amr executions %s resolved for the client session: completed in this authentication %s, completed in the user session %s", resolved, current, completed);

try {
return JsonSerialization.writeValueAsString(resolved);
} catch (IOException e) {
throw new IllegalStateException(e);
}
}

/**
* Get the configured authenticator reference values for executions resolved by
* {@link #resolveAuthenticationExecutions(AuthenticationSessionModel, UserSessionModel, RealmModel)}. The max age was
* applied when they were resolved, so it is not applied again. An execution without a configured value is skipped.
*
* @param executionIds The authenticator execution ids
* @param realmModel The realm the executions are configured in
* @return The list of amr values.
*/
public static List<String> getAuthenticationExecutionReferences(Collection<String> executionIds, RealmModel realmModel) {
return executionIds.stream()
.map(executionId -> {
Map<String, String> config = getExecutionConfig(executionId, realmModel);
return config == null ? null : config.get(Constants.AUTHENTICATION_EXECUTION_REFERENCE_VALUE);
})
.filter(ref -> ref != null && !ref.isEmpty())
.collect(Collectors.toList());
}

/**
* Decide whether an execution completed by an earlier authentication in the SSO session is still reported by an
* authentication completing now. A max age of 0, the default, never carries over: the reference value belongs to
* the authentication that completed the execution only. A positive max age carries over while the execution
* completed within that many seconds, inclusive.
*
* @param config The authenticator execution config
* @param completedAt The time the execution completed
* @return True if the authentication completing now reports the execution
*/
public static boolean carriesOver(Map<String, String> config, Integer completedAt) {
return carriesOver(config, completedAt, Time.currentTime());
}

/**
* {@link #carriesOver(Map, Integer)} against an explicit current time.
*
* @param config The authenticator execution config
* @param completedAt The time the execution completed
* @param now The time the authentication completes
* @return True if the authentication completing at {@code now} reports the execution
*/
public static boolean carriesOver(Map<String, String> config, Integer completedAt, int now) {
try {
int maxAge = Integer.parseInt(config.getOrDefault(Constants.AUTHENTICATION_EXECUTION_REFERENCE_MAX_AGE, "0"));
return maxAge > 0 && completedAt + maxAge >= now;
} catch (NumberFormatException e) {
logger.warnf("invalid authentication execution max age '%s'", config.get(Constants.AUTHENTICATION_EXECUTION_REFERENCE_MAX_AGE));
return false;
}
}

private static Map<String, String> getExecutionConfig(String executionId, RealmModel realm) {
AuthenticationExecutionModel execution = realm.getAuthenticationExecutionById(executionId);
if (execution == null || execution.getAuthenticatorConfig() == null) {
return null;
}
AuthenticatorConfigModel config = realm.getAuthenticatorConfigById(execution.getAuthenticatorConfig());
return config == null ? null : config.getConfig();
}

/**
* Get the configured authenticator reference values for the specified completed executions, each subject to its
* configured max age as of now. Used for client sessions without resolved executions. If no
* value is configured for the execution, null is returned instead of throwing an error.
*
* @param executions List of authenticator execution ids
* @param executions Map of authenticator execution ids to the time the execution completed
* @param realmModel The realm the executions are configured in
* @return The list of amr values.
*/
Expand All @@ -64,7 +171,7 @@ public static List<String> getAuthenticationExecutionReferences(Map<String, Inte
}

/**
* Check if the AMR is still valid by determining if the execution time + the configured max age is less than the current time
* Check if a carried over AMR is still valid by determining if the execution time + the configured max age is not yet in the past
* @param config The authenticator execution config
* @param authTime The time that the authentication occurred
* @return True if the amr value is still valid for this session
Expand Down
Loading
Loading