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 @@ -205,6 +205,8 @@ public enum Feature {

SCIM_API("Exposes a SCIM API for managing realm resources on a per-realm basis", Type.DEFAULT),

SCIM_GROUP_MEMBERSHIP_CLAIMS("Groups owned by the SCIM client that created them, with full member lists on PUT", Type.EXPERIMENTAL, SCIM_API),

RESOURCE_INDICATORS("Resource Indicators for OAuth 2.0", Type.EXPERIMENTAL),

IDENTITY_BROKERING_API_V1("Identity Brokering API V1", Type.DEFAULT, 1, true, null, null),
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -46,6 +46,7 @@ A successful response returns the created group with a `201 Created` status.

NOTE: Group members cannot be specified during group creation. Attempting to include members in the `POST`
request results in a `400 Bad Request` error. Use the `PATCH` method to add members after creating the group.
Realms where groups are owned by a SCIM client accept members on `POST`. See <<_scim_membership_claims_,Groups owned by a SCIM client>>.

If a group with the same `displayName` already exists, the API returns a `409 Conflict` response with
`scimType: "uniqueness"`.
Expand Down Expand Up @@ -93,6 +94,8 @@ curl -X PUT http://localhost:8080/realms/myrealm/scim/v2/Groups/{id} \

NOTE: Group members cannot be modified through `PUT` requests. Attempting to include members in the `PUT`
request results in a `400 Bad Request` error. Use the `PATCH` method to manage group members.
Realms where groups are owned by a SCIM client accept `members` on `PUT` from the client that owns the group. See
<<_scim_membership_claims_,Groups owned by a SCIM client>>.

== Partially updating a group

Expand Down Expand Up @@ -232,6 +235,85 @@ NOTE: Organization-related groups cannot have their members managed through the
remove members from an organization group returns a `400 Bad Request` error. Use the Organization API to manage
organization group memberships.

[[_scim_membership_claims_]]
=== Groups owned by a SCIM client

Some identity providers send the full member list of a group on every update, with `PUT`. Okta applications built
with the App Integration Wizard work this way and cannot be switched to `PATCH`. A realm can accept these requests
by letting the SCIM client that creates a group own it. Two switches must both be on:

* the experimental server feature `scim-group-membership-claims`, for example `--features=scim-group-membership-claims`;
* the realm attribute `scimGroupMembershipClaims`, set to `true`.

Both are off by default. While either is off, the SCIM endpoints behave as described in the rest of this chapter.

The realm attribute has no toggle in the Admin Console. Set it with the Admin REST API. A realm update replaces the
realm's attributes with the ones it sends, so read the realm first, add the attribute, and send the whole
representation back:

[source,bash]
----
curl -s http://localhost:8080/admin/realms/myrealm \
-H "Authorization: Bearer $ADMIN_TOKEN" \
| jq '.attributes.scimGroupMembershipClaims = "true"' \
| curl -X PUT http://localhost:8080/admin/realms/myrealm \
-H "Authorization: Bearer $ADMIN_TOKEN" \
-H "Content-Type: application/json" \
-d @-
----

To turn it off, set the attribute to `false` the same way.

When it is on, the SCIM client that creates a group with `POST /Groups` owns that group. The client is the one the
access token was issued to. {project_name} stores the owner by the client's Client ID. The rules are:

* A `POST` can include `members`. The group is created with them, and the caller becomes its owner.
* The owner can send the full member list with `PUT`, or with a `PATCH` that replaces `members`. A `replace` with no
path, or with the Group schema URN as its path, and `members` in its `value` counts the same. {project_name} adds
the listed users who are not members yet, and removes the members who are not listed.
* The owner can also use `PATCH` `add` and `remove`. A `remove` can name the members with a
`members[value eq "{userId}"]` filter in the path or, as Microsoft Entra ID does, with a `value` listing them.
A `remove` on `members` with neither removes every member that the owner may remove. An empty `value` list
removes nobody.
* Service accounts and administrators stay in the group. When the owner's full list leaves one out, that member is
kept, the rest of the request is applied, and the request succeeds. A request that names one in an `add` or a
`remove`, or lists one who is not a member yet, is rejected with a `400 Bad Request` or `403 Forbidden` error, as
in a realm without owners. Listing one who is already a member changes nothing and is accepted.
* A listed user that does not exist rejects the whole request. Every member in a request is checked before anything
changes. If one member is invalid, nothing in the request is applied.
* Requests that change the members of the same group are processed one after the other.
* Any other SCIM client that sends a `PUT`, a `PATCH` or a `DELETE` for an owned group gets a `403 Forbidden` error
saying that the group is managed by another SCIM client. Deleting a group deletes its subgroups, so a client also
gets a `403 Forbidden` error when it deletes a group that has a group owned by another client anywhere below it.
* A user's `groups` cannot be used to change the members of an owned group, as RFC 7643 section 4.1.2 describes.
A `POST`, `PUT` or `PATCH` on `/Users` that would add the user to an owned group, or remove the user from one, is
rejected with a `400 Bad Request` error and `scimType: "mutability"`. A request that sends no `groups`, or that
sends the user's current direct groups unchanged, is accepted. Changes to groups that no SCIM client owns work as
before.
* A read of an owned group shows every member to every client, without `attributes=members`. A client that pushes a
full member list therefore reads back the full list. Members are left out when the request excludes them
(`excludedAttributes=members`), or when `attributes` names other attributes but not `members`.

A group that no SCIM client owns behaves as described in the rest of this chapter. Such a group was created before
the switches were turned on, or by an administrator. Any SCIM client can change its members with `PATCH` `add` and
`remove`, a `PUT` with `members` is rejected, and any SCIM client with permission to manage groups can delete it.
A client never becomes the owner of an existing group. An identity provider that offers to link a group it pushes to
an existing group, as Okta does, cannot manage that group's members with full lists. Let the identity provider
create the group instead.

The owner is stored by Client ID, so it outlives the client. If the owning client is deleted, its groups keep the
owner, and no other SCIM client can change or delete them. A client created again with the same Client ID owns them
again. Renaming a client's Client ID has the same effect as deleting it: its groups have no reachable owner until a
client with the old Client ID exists again.

Administrators are not limited by these rules yet. An administrator can change the members of an owned group in the
Admin Console or with the Admin REST API. The owner's next full list, sent with `PUT` or with a `PATCH` that replaces
`members`, then overwrites that change, except for service accounts and administrators, who stay.

NOTE: Memberships stored outside the {project_name} database, for example by an LDAP group mapper, cannot be
managed this way. A request that would remove one is rejected before anything changes. A request that would add one
returns an error, but a change already written to the external store is not undone.

== Deleting a group

[source,bash]
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -338,6 +338,10 @@ All other comparison operators are not supported.
You can manage a user's group memberships directly through the user resource. Group membership can also be managed
from the group side using the `/Groups` endpoint. See <<_scim_managing_groups_,Managing groups>> for details.

NOTE: In a realm where groups are owned by a SCIM client, a request in this section that would add a user to an
owned group, or remove the user from one, is rejected with a `400 Bad Request` error and `scimType: "mutability"`.
Groups that no SCIM client owns are not affected. See <<_scim_membership_claims_,Groups owned by a SCIM client>>.

=== Adding a user to groups on creation

When creating a user, you can specify the groups the user should belong to:
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,73 @@
/*
* Copyright 2026 Red Hat, Inc. and/or its affiliates
* and other contributors as indicated by the @author tags.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

package org.keycloak.models.jpa.entities;

import java.util.Objects;

import jakarta.persistence.Column;
import jakarta.persistence.Entity;
import jakarta.persistence.Id;
import jakarta.persistence.Table;

/**
* The SCIM client that created a group, and so owns it.
*
* <p>The owner is stored by the client's {@code clientId}, not by its internal id, and has no foreign key to the
* client. Deleting the client keeps the row, and a client created again with the same {@code clientId} owns the group
* again. The database removes the row together with the group. A group without a row was created some other way, for
* example by an administrator, or before the realm turned ownership on.
*/
@Entity
@Table(name = "SCIM_GROUP_OWNER")
public class ScimGroupOwnerEntity {

@Id
@Column(name = "GROUP_ID", length = 36)
protected String groupId;

@Column(name = "CLIENT_ID", nullable = false)
protected String clientId;

public ScimGroupOwnerEntity() {
}

public ScimGroupOwnerEntity(String groupId, String clientId) {
this.groupId = groupId;
this.clientId = clientId;
}

public String getGroupId() {
return groupId;
}

public String getClientId() {
return clientId;
}

@Override
public boolean equals(Object o) {
if (this == o) return true;
if (!(o instanceof ScimGroupOwnerEntity that)) return false;
return Objects.equals(groupId, that.groupId);
}

@Override
public int hashCode() {
return Objects.hashCode(groupId);
}
}
22 changes: 22 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,26 @@
<customChange class="org.keycloak.connections.jpa.updater.liquibase.custom.JpaUpdate27_0_0_OidcIssuerMigration"/>
</changeSet>

<!-- The SCIM client that created a group, by clientId. Removed with the group. Kept when the client is deleted. -->
<changeSet author="keycloak" id="27.0.0-scim-group-owner">
<preConditions onFail="MARK_RAN" onSqlOutput="TEST">
<not>
<tableExists tableName="SCIM_GROUP_OWNER"/>
</not>
</preConditions>
<createTable tableName="SCIM_GROUP_OWNER">
<column name="GROUP_ID" type="VARCHAR(36)">
<constraints nullable="false"/>
</column>
<column name="CLIENT_ID" type="VARCHAR(255)">
<constraints nullable="false"/>
</column>
</createTable>
<addPrimaryKey tableName="SCIM_GROUP_OWNER" columnNames="GROUP_ID" constraintName="PK_SCIM_GROUP_OWNER"/>
<addForeignKeyConstraint baseTableName="SCIM_GROUP_OWNER" baseColumnNames="GROUP_ID"
constraintName="FK_SCIM_GRP_OWNER_GROUP"
referencedTableName="KEYCLOAK_GROUP" referencedColumnNames="ID"
onDelete="CASCADE"/>
</changeSet>

</databaseChangeLog>
Original file line number Diff line number Diff line change
Expand Up @@ -5,4 +5,13 @@
*/
public class ForbiddenException extends RuntimeException{

public ForbiddenException() {
}

/**
* @param message the detail returned to the caller in the error response
*/
public ForbiddenException(String message) {
super(message);
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -156,6 +156,14 @@ default List<MembershipChange> pollMembershipChanges() {
return List.of();
}

/**
* Returns the group membership changes made by the last {@link #create} call that the caller should record as
* {@code GROUP_MEMBERSHIP} admin events, then clears them. By default a create reports none.
*/
default List<MembershipChange> pollCreateMembershipChanges() {
return List.of();
}

/**
* Returns the admin event {@link ResourceType} for this SCIM resource type.
* By default, derives it from {@link #getName()} by converting to uppercase and matching against known values.
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -214,6 +214,29 @@ void clearMembershipChanges() {
membershipChanges.clear();
}

void recordMembershipChange(MembershipChange change) {
membershipChanges.add(change);
}

/**
* The members of {@code model} as a read that asks for {@code members} returns them.
*/
List<Member> readMembers(GroupModel model) {
@SuppressWarnings("unchecked")
List<UserModel> users = (List<UserModel>) getAttributeValue(model, "members");
List<Member> members = new ArrayList<>();

for (UserModel user : users) {
Member member = new Member();
member.setValue(user.getId());
member.setDisplay(user.getUsername());
member.setType("User");
members.add(member);
}

return members;
}

private void setTimestamps(Group resource, GroupModel model) {
Long createdTimestamp = model.getCreatedTimestamp();
if (createdTimestamp != null) {
Expand All @@ -225,7 +248,7 @@ private void setTimestamps(Group resource, GroupModel model) {
}
}

private static void checkGroupMembershipPermission(Permissions permissions, GroupModel group) {
static void checkGroupMembershipPermission(Permissions permissions, GroupModel group) {
if (GroupModel.Type.ORGANIZATION.equals(group.getType()) && group.getOrganization() != null) {
throw new ModelValidationException("Invalid group");
}
Expand All @@ -237,7 +260,7 @@ private static void checkGroupMembershipPermission(Permissions permissions, Grou
}
}

private void checkRequireManageGroupMembership(Permissions permissions, UserModel model) {
void checkRequireManageGroupMembership(Permissions permissions, UserModel model) {
if (model.isServiceAccount()) {
throw new ForbiddenException();
}
Expand All @@ -261,7 +284,7 @@ private void checkGroupHasNoServiceAccounts(RealmModel realm, GroupModel group)
.forEach(subGroup -> checkGroupHasNoServiceAccounts(realm, subGroup));
}

private boolean canViewUser(UserModel u) {
boolean canViewUser(UserModel u) {
if (u.isServiceAccount()) {
return false;
}
Expand Down
Loading