NokiaTube | New address | Mode Desktop | Off high quality for Nokia Browser
Skip to content
Open
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
2 changes: 2 additions & 0 deletions common/src/main/java/org/keycloak/common/Profile.java
Original file line number Diff line number Diff line change
Expand Up @@ -130,6 +130,8 @@ public enum Feature {

TRANSIENT_USERS("Transient users for brokering", Type.EXPERIMENTAL),

USER_LAST_SUCCESSFUL_AUTHENTICATION("Track last successful authentication per user", Type.EXPERIMENTAL),

LOGIN_FAILURES_V1("In-memory login failures", Type.DEPRECATED, 1, FeatureUpdatePolicy.SHUTDOWN),
LOGIN_FAILURES_V2("Persistent login failures", Type.DEFAULT, 2, FeatureUpdatePolicy.SHUTDOWN),

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,7 @@ public class UserRepresentation extends AbstractUserRepresentation{
protected String self; // link
protected String origin;
protected Long createdTimestamp;
protected Long lastSuccessfulAuthentication;
protected Boolean totp;
protected String federationLink;
protected String serviceAccountClientId; // For rep, it points to clientId (not DB ID)
Expand Down Expand Up @@ -73,6 +74,7 @@ public UserRepresentation(UserRepresentation rep) {

this.self = rep.getSelf();
this.createdTimestamp = rep.getCreatedTimestamp();
this.lastSuccessfulAuthentication = rep.getLastSuccessfulAuthentication();
this.enabled = rep.isEnabled();
this.totp = rep.isTotp();
this.federationLink = rep.getFederationLink();
Expand Down Expand Up @@ -111,6 +113,19 @@ public void setCreatedTimestamp(Long createdTimestamp) {
this.createdTimestamp = createdTimestamp;
}

/**
* Timestamp of the user's last successful authentication, or {@code null} if the user has
* never authenticated since this feature was introduced. System-managed; this field is
* ignored on create/update requests.
*/
public Long getLastSuccessfulAuthentication() {
return lastSuccessfulAuthentication;
}

public void setLastSuccessfulAuthentication(Long lastSuccessfulAuthentication) {
this.lastSuccessfulAuthentication = lastSuccessfulAuthentication;
}

@Deprecated
public Boolean isTotp() {
return totp;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -178,6 +178,24 @@ public void setLastModifiedTimestamp(Long timestamp) {
updated.setLastModifiedTimestamp(timestamp);
}

@Override
public Long getLastSuccessfulAuthentication() {
if (updated != null) return updated.getLastSuccessfulAuthentication();
return cached.getLastSuccessfulAuthentication();
}

@Override
public void setLastSuccessfulAuthentication(Long timestamp) {
// NOTE: this is written on every successful login, so going through getDelegateForUpdate()
// invalidates this user's cache entry cluster-wide on every login. Worth revisiting
// (e.g. a write-through path that bypasses cache invalidation) before this feature is stabilized.
if (updated == null && Objects.equals(cached.getLastSuccessfulAuthentication(), timestamp)) {
return;
}
getDelegateForUpdate();
updated.setLastSuccessfulAuthentication(timestamp);
}

@Override
public boolean isEnabled() {
if (updated != null) return updated.isEnabled();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -46,6 +46,7 @@ public class CachedUser extends AbstractExtendableRevisioned implements InRealm
private final String realm;
private final Long createdTimestamp;
private final Long lastModifiedTimestamp;
private final Long lastSuccessfulAuthentication;
private final boolean emailVerified;
private final boolean enabled;
private final String federationLink;
Expand All @@ -63,6 +64,7 @@ public CachedUser(long revision, RealmModel realm, UserModel user, int notBefore
this.realm = realm.getId();
this.createdTimestamp = user.getCreatedTimestamp();
this.lastModifiedTimestamp = user.getLastModifiedTimestamp();
this.lastSuccessfulAuthentication = user.getLastSuccessfulAuthentication();
this.emailVerified = user.isEmailVerified();
this.enabled = user.isEnabled();
this.federationLink = user.getFederationLink();
Expand Down Expand Up @@ -113,6 +115,10 @@ public Long getLastModifiedTimestamp() {
return lastModifiedTimestamp;
}

public Long getLastSuccessfulAuthentication() {
return lastSuccessfulAuthentication;
}

public String getEmail() {
return eagerLoadedAttributes.getFirst(UserModel.EMAIL);
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -1338,6 +1338,12 @@ private List<Predicate> predicates(Map<String, String> attributes, Root<UserEnti
case UserModel.CREATED_BEFORE:
predicates.add(builder.lessThanOrEqualTo(root.get("createdTimestamp"), Long.parseLong(value)));
break;
case UserModel.LAST_SUCCESSFUL_AUTHENTICATION_AFTER:
predicates.add(builder.greaterThanOrEqualTo(root.get("lastSuccessfulAuthentication"), Long.parseLong(value)));
break;
case UserModel.LAST_SUCCESSFUL_AUTHENTICATION_BEFORE:
predicates.add(builder.lessThanOrEqualTo(root.get("lastSuccessfulAuthentication"), Long.parseLong(value)));
break;
default:
// All unknown attributes will be assumed as custom attributes
Join<UserEntity, UserAttributeEntity> attributesJoin = root.join("attributes", JoinType.LEFT);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -129,6 +129,16 @@ public void setLastModifiedTimestamp(Long timestamp) {
user.setLastModifiedTimestamp(timestamp);
}

@Override
public Long getLastSuccessfulAuthentication() {
return user.getLastSuccessfulAuthentication();
}

@Override
public void setLastSuccessfulAuthentication(Long timestamp) {
user.setLastSuccessfulAuthentication(timestamp);
}

@Override
public boolean isEnabled() {
return user.isEnabled();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -78,6 +78,8 @@ public class UserEntity {
protected Long createdTimestamp;
@Column(name = "LAST_MODIFIED_TIMESTAMP")
protected Long lastModifiedTimestamp;
@Column(name = "LAST_SUCCESSFUL_AUTH")
protected Long lastSuccessfulAuthentication;
@Nationalized
@Column(name = "LAST_NAME")
protected String lastName;
Expand Down Expand Up @@ -159,6 +161,14 @@ public void setLastModifiedTimestamp(Long timestamp) {
lastModifiedTimestamp = timestamp;
}

public Long getLastSuccessfulAuthentication() {
return lastSuccessfulAuthentication;
}

public void setLastSuccessfulAuthentication(Long timestamp) {
lastSuccessfulAuthentication = timestamp;
}

public String getFirstName() {
return firstName;
}
Expand Down
11 changes: 11 additions & 0 deletions model/jpa/src/main/resources/META-INF/jpa-changelog-27.0.0.xml
Original file line number Diff line number Diff line change
Expand Up @@ -25,4 +25,15 @@
<customChange class="org.keycloak.connections.jpa.updater.liquibase.custom.JpaUpdate27_0_0_OidcIssuerMigration"/>
</changeSet>

<changeSet author="keycloak" id="27.0.0-52319-user-last-successful-auth">
<preConditions onFail="MARK_RAN" onSqlOutput="TEST">
<not>
<columnExists tableName="USER_ENTITY" columnName="LAST_SUCCESSFUL_AUTH"/>
</not>
</preConditions>
<addColumn tableName="USER_ENTITY">
<column name="LAST_SUCCESSFUL_AUTH" type="BIGINT"/>
</addColumn>
</changeSet>

</databaseChangeLog>
Original file line number Diff line number Diff line change
Expand Up @@ -1048,6 +1048,9 @@ public UserModel createUser(RealmModel newRealm, UserRepresentation userRep) {
if (userRep.getCreatedTimestamp() != null) {
user.setCreatedTimestamp(userRep.getCreatedTimestamp());
}
if (userRep.getLastSuccessfulAuthentication() != null) {
user.setLastSuccessfulAuthentication(userRep.getLastSuccessfulAuthentication());
}
user.setEmail(userRep.getEmail());
if (userRep.isEmailVerified() != null) user.setEmailVerified(userRep.isEmailVerified());
user.setFirstName(userRep.getFirstName());
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -55,6 +55,7 @@ public abstract class AbstractUserAdapterFederatedStorage extends UserModelDefau
public static String EMAIL_VERIFIED_ATTRIBUTE = "EMAIL_VERIFIED";
public static String CREATED_TIMESTAMP_ATTRIBUTE = "CREATED_TIMESTAMP";
public static String ENABLED_ATTRIBUTE = "ENABLED";
public static String LAST_SUCCESSFUL_AUTHENTICATION_ATTRIBUTE = "LAST_SUCCESSFUL_AUTHENTICATION";


protected KeycloakSession session;
Expand Down Expand Up @@ -311,6 +312,22 @@ public void setCreatedTimestamp(Long timestamp) {

}

@Override
public Long getLastSuccessfulAuthentication() {
String val = getFirstAttribute(LAST_SUCCESSFUL_AUTHENTICATION_ATTRIBUTE);
if (val == null) return null;
else return Long.valueOf(val);
Comment on lines +317 to +319
}

@Override
public void setLastSuccessfulAuthentication(Long timestamp) {
if (timestamp == null) {
setSingleAttribute(LAST_SUCCESSFUL_AUTHENTICATION_ATTRIBUTE, null);
} else {
setSingleAttribute(LAST_SUCCESSFUL_AUTHENTICATION_ATTRIBUTE, Long.toString(timestamp));
}
}

@Override
public void setSingleAttribute(String name, String value) {
if (UserModel.USERNAME.equals(name)) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -317,6 +317,7 @@ public static UserRepresentation toRepresentation(KeycloakSession session, Realm
rep.setUsername(user.getUsername());
}
rep.setCreatedTimestamp(user.getCreatedTimestamp());
rep.setLastSuccessfulAuthentication(user.getLastSuccessfulAuthentication());
Comment thread
hypery2k marked this conversation as resolved.
Resolved
if (setUserAttributes) {
rep.setLastName(user.getLastName());
}
Expand Down Expand Up @@ -382,6 +383,7 @@ public static UserRepresentation toBriefRepresentation(UserModel user, UserRepre
rep.setUsername(user.getUsername());
}
rep.setCreatedTimestamp(user.getCreatedTimestamp());
rep.setLastSuccessfulAuthentication(user.getLastSuccessfulAuthentication());
if (setUserAttributes) {
rep.setLastName(user.getLastName());
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -43,6 +43,7 @@
*/
public abstract class AbstractInMemoryUserAdapter extends UserModelDefaultMethods {
private Long createdTimestamp = Time.currentTimeMillis();
private Long lastSuccessfulAuthentication;
private boolean emailVerified;
private boolean enabled;

Expand Down Expand Up @@ -109,6 +110,19 @@ public void setCreatedTimestamp(Long timestamp) {
this.createdTimestamp = timestamp;
}

// Not durable across requests for non-imported providers backed by this adapter (e.g. non-imported
// LDAP) - there's no writable backing store to persist to, only this request-scoped instance.
@Override
public Long getLastSuccessfulAuthentication() {
return lastSuccessfulAuthentication;
}

@Override
public void setLastSuccessfulAuthentication(Long timestamp) {
checkReadonly();
this.lastSuccessfulAuthentication = timestamp;
}

@Override
public boolean isEnabled() {
return enabled;
Expand Down
14 changes: 14 additions & 0 deletions server-spi/src/main/java/org/keycloak/models/UserModel.java
Original file line number Diff line number Diff line change
Expand Up @@ -48,10 +48,13 @@ public interface UserModel extends RoleMapperModel, Model {
String EXACT = "keycloak.session.realm.users.query.exact";
String CREATED_AFTER = "keycloak.session.realm.users.query.created_after";
String CREATED_BEFORE = "keycloak.session.realm.users.query.created_before";
String LAST_SUCCESSFUL_AUTHENTICATION_AFTER = "keycloak.session.realm.users.query.last_successful_authentication_after";
String LAST_SUCCESSFUL_AUTHENTICATION_BEFORE = "keycloak.session.realm.users.query.last_successful_authentication_before";
String DISABLED_REASON = "disabledReason";
//attribute name used to mark a temporary admin user/service account as temporary
String IS_TEMP_ADMIN_ATTR_NAME = "is_temporary_admin";
String CREATED_TIMESTAMP = "createdTimestamp";
String LAST_SUCCESSFUL_AUTHENTICATION = "lastSuccessfulAuthentication";

Comparator<UserModel> COMPARE_BY_USERNAME = Comparator.comparing(UserModel::getUsername, String.CASE_INSENSITIVE_ORDER);

Expand Down Expand Up @@ -97,6 +100,17 @@ default Long getLastModifiedTimestamp() {
default void setLastModifiedTimestamp(Long timestamp) {
}

/**
* Get timestamp of the user's last successful authentication. May be null if the user has never
* authenticated since this feature was introduced.
*/
default Long getLastSuccessfulAuthentication() {
return null;
}

default void setLastSuccessfulAuthentication(Long timestamp) {
}

boolean isEnabled();

void setEnabled(boolean enabled);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -229,6 +229,16 @@ public void setCreatedTimestamp(Long timestamp){
delegate.setCreatedTimestamp(timestamp);
}

@Override
public Long getLastSuccessfulAuthentication() {
return delegate.getLastSuccessfulAuthentication();
}

@Override
public void setLastSuccessfulAuthentication(Long timestamp) {
delegate.setLastSuccessfulAuthentication(timestamp);
}

@Override
public Stream<GroupModel> getGroupsStream() {
return delegate.getGroupsStream();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -17,13 +17,19 @@

package org.keycloak.protocol.oidc.grants;

import java.time.Duration;
import java.time.OffsetDateTime;
import java.time.ZoneOffset;
import java.time.format.DateTimeFormatter;
import java.time.format.DateTimeParseException;
import java.util.Collections;
import java.util.Set;

import jakarta.ws.rs.core.Response;

import org.keycloak.OAuthErrorException;
import org.keycloak.authentication.AuthenticationProcessor;
import org.keycloak.common.Profile;
import org.keycloak.common.constants.ServiceAccountConstants;
import org.keycloak.events.Details;
import org.keycloak.events.Errors;
Expand All @@ -44,6 +50,7 @@
import org.keycloak.services.managers.UserSessionManager;
import org.keycloak.sessions.AuthenticationSessionModel;
import org.keycloak.sessions.RootAuthenticationSessionModel;
import org.keycloak.userprofile.LoginActivityAttributeRegistrar;

import org.jboss.logging.Logger;

Expand Down Expand Up @@ -153,6 +160,7 @@ public Response process(Context context) {

// client credentials grant always removes the online session
clientSessionCtx.getClientSession().setNote(AuthenticationProcessor.FIRST_OFFLINE_ACCESS, Boolean.TRUE.toString());
recordClientLastLogin();
return createTokenResponse(clientUser, userSession, clientSessionCtx, scope, true,
responseBuilder -> new ServiceAccountTokenResponseContext(formParams, clientSessionCtx, responseBuilder));
}
Expand All @@ -172,6 +180,40 @@ protected boolean useRefreshToken() {
return clientConfig.isUseRefreshTokenForClientCredentialsGrant();
}

/**
* Minimum spacing between writes of {@value LoginActivityAttributeRegistrar#CLIENT_LAST_LOGIN_ATTRIBUTE}.
* {@code ClientModel#setAttribute} triggers cluster-wide invalidation of that client's cache entry, so
* writing on every single client-credentials request would make high-volume service accounts evict
* shared client configuration continuously. A per-minute resolution is enough for "last login" auditing.
*/
private static final Duration MIN_CLIENT_LAST_LOGIN_UPDATE_INTERVAL = Duration.ofMinutes(1);

/**
* Records this client's last successful client-credentials (service account) login as a
* {@value LoginActivityAttributeRegistrar#CLIENT_LAST_LOGIN_ATTRIBUTE} attribute, in the same
* format previously written by the community keycloak-auditor SPI plugin on {@code CLIENT_LOGIN}
* events, so deployments already using that plugin keep continuity when they switch to this
* native implementation. Gated behind {@link Profile.Feature#USER_LAST_SUCCESSFUL_AUTHENTICATION}.
*/
private void recordClientLastLogin() {
if (!Profile.isFeatureEnabled(Profile.Feature.USER_LAST_SUCCESSFUL_AUTHENTICATION)) {
return;
}
OffsetDateTime now = OffsetDateTime.now(ZoneOffset.UTC);
String existing = client.getAttribute(LoginActivityAttributeRegistrar.CLIENT_LAST_LOGIN_ATTRIBUTE);
if (existing != null) {
try {
OffsetDateTime last = OffsetDateTime.parse(existing, DateTimeFormatter.ISO_DATE_TIME);
if (Duration.between(last, now).compareTo(MIN_CLIENT_LAST_LOGIN_UPDATE_INTERVAL) < 0) {
return;
}
} catch (DateTimeParseException e) {
// Malformed value (shouldn't normally happen) - fall through and overwrite it.
}
}
client.setAttribute(LoginActivityAttributeRegistrar.CLIENT_LAST_LOGIN_ATTRIBUTE, DateTimeFormatter.ISO_DATE_TIME.format(now));
}

/**
* Setting a client note with authorization_details to support custom protocol mappers using RAR (Rich Authorization Request)
* until RAR is fully implemented.
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -179,6 +179,7 @@ public Response process(Context context) {

event.success();
AuthenticationManager.logSuccess(session, authSession);
AuthenticationManager.recordLastSuccessfulAuthentication(session, realm, user, client);

return cors.add(Response.ok(res, MediaType.APPLICATION_JSON_TYPE));
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -218,6 +218,8 @@ public Response process(Context context) {
int authTime = Time.currentTime();
userSession.setNote(AuthenticationManager.AUTH_TIME, String.valueOf(authTime));

AuthenticationManager.recordLastSuccessfulAuthentication(session, realm, user, client);

return createTokenResponse(user, userSession, clientSessionCtx, scopeParam, true,s -> {return new BackchannelTokenResponseContext(request, formParams, clientSessionCtx, s);});

}
Expand Down
Loading