8000 Support the password attribute in the SCIM User resource by costa-chown · Pull Request #55681 · keycloak/keycloak · GitHub
[go: up one dir, main page]

Skip to content

Navigation Menu

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
7 changes: 7 additions & 0 deletions docs/documentation/release_notes/topics/27_0_0.adoc
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,13 @@ This removes the need for a separate API call to discover the service account us
The dedicated `GET /admin/realms/\{realm}/clients/\{id}/service-account-user` endpoint has been removed.
See the upgrading guide for migration details.

== Passwords through SCIM

The SCIM `/Users` endpoint now supports the `password` attribute of the core user schema, and the Service Provider
Configuration reports `changePassword` as supported. A provisioning client can set the password of a user when it
creates the user, with a full replace and with a `PATCH` operation. The password policy of the realm applies, and the
password is never returned. For more details, see the link:{adminguide_link}#_scim_setting_password_[{adminguide_name}].

= Security and Standards

== Post-quantum WebAuthn signatures (experimental)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,7 @@ A successful response returns the capabilities of the SCIM API, including suppor
"maxResults": 100
},
"changePassword": {
"supported": false
"supported": true
},
"sort": {
"supported": false
Expand Down Expand Up @@ -63,10 +63,9 @@ capabilities defined by RFC 7644 are *not* supported in this release:
are returned in the default order of the underlying store.
* *ETag / resource versioning* (`etag.supported` is `false`). Resources do not carry a `meta.version`, and conditional
requests such as `If-Match` are not honored.
* *Password changes* (`changePassword.supported` is `false`). The `password` attribute cannot be set or updated through
SCIM. Manage credentials through the Admin Console or the Admin REST API instead.

The `patch` and `filter` capabilities are supported. List and search requests return at most `100` results per request
The `patch`, `filter` and `changePassword` capabilities are supported. For setting passwords, see
<<_scim_setting_password_,Setting a password>>. List and search requests return at most `100` results per request
(`filter.maxResults`); use pagination to retrieve additional results. See <<_scim_filtering_resources,Filtering resources>>.

Future releases may allow customization of certain capabilities, such as supported authentication schemes or maximum filter results.
Expand Down
42 changes: 42 additions & 0 deletions docs/documentation/server_admin/topics/scim/managing-users.adoc
Original file line number Diff line number Diff line change
Expand Up @@ -43,6 +43,10 @@ given user account. When multiple email values are submitted, only the first val
| `externalId`
| (custom attribute)
| An identifier from an external system. Requires user profile configuration. See <<_scim_mapping_attributes_,Mapping attributes>>.

| `password`
| password credential
| Sets the password of the user. Write-only, never returned. See <<_scim_setting_password_,Setting a password>>.
|===

Additional name sub-attributes (`name.middleName`, `name.honorificPrefix`, `name.honorificSuffix`) can be mapped
Expand Down Expand Up @@ -333,6 +337,44 @@ NOTE: The `and` operator is not supported for any multivalued attributes because

All other comparison operators are not supported.

[[_scim_setting_password_]]
== Setting a password

The `password` attribute sets the password credential of the user, as the reset password endpoint of the Admin REST
API does: the new password replaces the current one, and the current password is not required. Use it from trusted
provisioning clients. The attribute is write-only (`mutability: writeOnly`, `returned: never`), so it is never
included in a response, also not when requested with the `attributes` parameter.

The password can be set when creating a user (`POST`), with a full replace (`PUT`), and with a `PATCH` operation:

[source,bash]
----
curl -X PATCH http://localhost:8080/realms/myrealm/scim/v2/Users/{id} \
-H "Authorization: Bearer $ACCESS_TOKEN" \
-H "Content-Type: application/scim+json" \
-d '{
"schemas": ["urn:ietf:params:scim:api:messages:2.0:PatchOp"],
"Operations": [
{
"op": "replace",
"path": "password",
"value": "{new-password}"
}
]
}'
----

A `PUT` request without the `password` attribute keeps the current password.

The password policy of the realm applies. A password that does not meet it, or an empty password, is rejected with a
`400 Bad Request` response and `scimType: "invalidValue"`, and the request changes nothing.

Only the password credential is affected. Other credentials of the user, such as OTP or WebAuthn, are not managed through SCIM.

NOTE: A password set through SCIM is always permanent. SCIM has no equivalent of a temporary password, so the
Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

If the UPDATE_PASSWORD parity gap is not fixed, this note should also say that an existing Update Password required action is not removed either, unlike the Admin REST API reset password endpoint, so a user with one pending still has to change the password that was just provisioned.

*Update Password* required action is not added to the user. To make the user choose a new password at the next login,
add the required action through the Admin Console or the Admin REST API.

== Managing group membership

You can manage a user's group memberships directly through the user resource. Group membership can also be managed
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -196,14 +196,29 @@ private void populateModel(M model, R resource) {
scimName = attribute.getSimpleName();
}

Object value = getJsonValue(valueNode, scimName);
Object value = attribute.isWriteOnly() ? getRawValue(valueNode, scimName) : getJsonValue(valueNode, scimName);

if (value != null) {
setValue(model, attribute, value);
}
}
}

/**
* Returns the value of a top-level attribute as sent, unlike {@link org.keycloak.utils.JsonUtils#getJsonValue},
* which trims text and drops blank text. A write-only attribute such as {@code password} must reach the model
* unchanged, so that a blank value can be rejected and surrounding whitespace is kept, as with PATCH.
*/
private Object getRawValue(ObjectNode node, String name) {
JsonNode value = node.get(name);

if (value == null || value.isNull()) {
return null;
}

return value.isTextual() ? value.textValue() : value;
}

private void populateResourceType(R resource, M model, List<String> requestedAttributes, List<String> excludedAttributes) {
for (Entry<String, Attribute<M, R>> entry : getAttributes().entrySet()) {
Attribute<M, R> attribute = entry.getValue();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -180,6 +180,19 @@ public boolean isImmutable() {
return Objects.equals(mutability, "immutable");
}

public boolean isWriteOnly() {
return Objects.equals(mutability, "writeOnly");
}

/**
* The mutability characteristic of the attribute as published in the schema (RFC 7643, Section 2.2).
*
* @return {@code immutable}, {@code writeOnly} or {@code readWrite}
*/
public String getMutability() {
return mutability == null ? "readWrite" : mutability;
}

public String getReturned() {
return returned;
}
Expand Down Expand Up @@ -473,6 +486,11 @@ public Builder<M, R> immutable() {
return this;
}

public Builder<M, R> writeOnly() {
this.mutability = "writeOnly";
return this;
}

public Builder<M, R> returned(String returned) {
this.returned = returned;
return this;
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
/*
* 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.scim.resource.spi;

/**
* Exception thrown when a value is not acceptable for an attribute, for example a password that does not meet the
* password policy of the realm. It maps to the SCIM error type {@code invalidValue} (RFC 7644, Section 3.12).
*
* <p>The message may be a key of the message bundle, formatted with the given parameters.
*/
public class ScimInvalidValueException extends RuntimeException {

private final Object[] parameters;

public ScimInvalidValueException(String message, Object... parameters) {
super(message);
this.parameters = parameters;
}

public Object[] getParameters() {
return parameters;
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -52,6 +52,9 @@ public class User extends ResourceTypeRepresentation {
@JsonProperty("emails")
private List<Email> emails;

@JsonProperty("password")
private String password;

@JsonProperty("groups")
private List<GroupMembership> groups;

Expand Down Expand Up @@ -226,4 +229,12 @@ public void addGroup(GroupMembership membership) {
}
groups.add(membership);
}

public String getPassword() {
return password;
}

public void setPassword(String password) {
this.password = password;
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -34,7 +34,7 @@ public ServiceProviderConfig getSingleton() {
config.setPatch(Supported.TRUE);
config.setEtag(Supported.FALSE);
config.setAuthenticationSchemes(List.of());
config.setChangePassword(Supported.FALSE);
config.setChangePassword(Supported.TRUE);
config.setCreatedTimestamp(Time.currentTimeMillis());
config.setSort(Supported.FALSE);
config.setFilter(getFilterSupport());
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -107,7 +107,7 @@ private void buildSchema(ModelSchema<?, ?> modelSchema) {
subAttr.setType(attribute.getType());
subAttr.setMultiValued(false);
subAttr.setReturned(attribute.getReturned());
subAttr.setMutability(attribute.isImmutable() ? "immutable" : "readWrite");
subAttr.setMutability(attribute.getMutability());
subAttr.setCaseExact(attribute.isCaseExact());
subAttr.setUniqueness(attribute.getUniqueness());

Expand All @@ -124,7 +124,7 @@ private void buildSchema(ModelSchema<?, ?> modelSchema) {
p.setName(k);
p.setType("complex");
p.setMultiValued(attribute.isMultivalued());
p.setMutability(attribute.isImmutable() ? "immutable" : "readWrite");
p.setMutability(attribute.getMutability());
p.setRequired(attribute.isRequired());
p.setCaseExact(attribute.isCaseExact());
p.setUniqueness(attribute.getUniqueness());
Expand All @@ -136,7 +136,7 @@ private void buildSchema(ModelSchema<?, ?> modelSchema) {
subAttr.setType(attribute.getType());
subAttr.setMultiValued(false);
subAttr.setReturned(attribute.getReturned());
subAttr.setMutability(attribute.isImmutable() ? "immutable" : "readWrite");
subAttr.setMutability(attribute.getMutability());
subAttr.setRequired(attribute.isRequired());
subAttr.setCaseExact(attribute.isCaseExact());
subAttr.setUniqueness(attribute.getUniqueness());
Expand Down Expand Up @@ -187,7 +187,7 @@ private Attribute createTopLevelAttribute(org.keycloak.scim.resource.schema.attr
attr.setType(attribute.getType());
attr.setMultiValued(attribute.isMultivalued());
attr.setReturned(attribute.getReturned());
attr.setMutability(attribute.isImmutable() ? "immutable" : "readWrite");
attr.setMutability(attribute.getMutability());
attr.setRequired(attribute.isRequired());
attr.setCaseExact(attribute.isCaseExact());
attr.setUniqueness(attribute.getUniqueness());
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,7 @@
import org.keycloak.scim.resource.Scim;
import org.keycloak.scim.resource.schema.attribute.Attribute;
import org.keycloak.scim.resource.spi.MembershipChange;
import org.keycloak.scim.resource.spi.ScimInvalidValueException;
import org.keycloak.scim.resource.user.Email;
import org.keycloak.scim.resource.user.GroupMembership;
import org.keycloak.scim.resource.user.Name;
Expand Down Expand Up @@ -153,6 +154,35 @@ protected Map<String, Attribute<UserModel, User>> getAttributeMappers() {
}
)
.build());
// RFC 7643, Section 4.1.1: write-only and never returned. The value is staged and set as a
// credential when the user is persisted, so it passes the password policy of the realm.
attributes.addAll(Attribute.<UserModel, User>simple("password")
.writeOnly()
.returned(Attribute.RETURNED_NEVER)
.caseExact()
Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

RFC 7643 Section 8.7.1 publishes "caseExact" : false for password. This sets it to true, and SchemaTest asserts true.

It has no functional effect here, since caseExact only drives filter case-folding in ScimJPAPredicateProvider and schema publication, but /Schemas is exactly what clients diff against the spec. I'd suggest dropping .caseExact() and updating the assertion.

.modelAttributeResolver(Attribute::getName)
Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Also, I think this has a side effect worth deciding on: this makes password resolvable as a filter path. ScimJPAPredicateProvider finds no password field on UserEntity and falls back to an EXISTS over UserAttributeEntity with name = 'password', so filter=password eq "x" always returns an empty page, and filter=password pr matches any user who happens to carry an unrelated user attribute named password.

No credential is exposed, so this is not a leak, but an empty page is a silently wrong answer to a filter RFC 7643 Section 4.1.1 explicitly contemplates ("set, replace, or compare (i.e., filter for equality)"). Rejecting filters on write-only attributes with invalidFilter would be clearer than answering them incorrectly.

.withModelSetter((TriConsumer<UserModel, String, String>) (model, name, value) -> {
if (value == null) {
return;
Comment thread
costa-chown marked this conversation as resolved.
Resolved
}
if (!(model instanceof UserModelAttributeRecorder recorder)) {
throw new IllegalStateException("password can only be set while the user is persisted");
}
if (value.isBlank()) {
throw new ScimInvalidValueException("password must not be blank");
Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This message, and "password cannot be removed", are raw English strings, while every other SCIM error message is a message bundle key.

}
recorder.setPassword(value);
}, (BiConsumer<User, Object>) (user, value) -> {
// never returned
})
// PATCH remove, also as the first half of a PATCH replace; rejected when the user is persisted
// unless a new password follows
.withModelRemover((model, name, values) -> {
if (model instanceof UserModelAttributeRecorder recorder) {
recorder.removePassword();
}
})
.build());
attributes.addAll(Attribute.<UserModel, User>simple("meta.created")
.timestamp()
.immutable()
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,8 @@
public class UserModelAttributeRecorder extends UserModelDelegate {

private final Map<String, List<String>> attributes;
private String password;
private boolean passwordRemoved;

public UserModelAttributeRecorder(UserModel delegate, Map<String, List<String>> attributes) {
super(delegate);
Expand All @@ -33,6 +35,34 @@ public void removeAttribute(String name) {
attributes.put(name, List.of());
}

/**
* Stages a new password. It is set as a credential once the user profile is persisted.
*/
public void setPassword(String password) {
this.password = password;
this.passwordRemoved = false;
}

/**
* Records a PATCH remove of the password and drops a password staged before it. A PATCH replace is a remove
* followed by an add, which stages the new password again.
*/
public void removePassword() {
Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Whether a password remove is rejected depends on where it falls in the operation list, since all operations share one recorder. testRemovePasswordRejected covers add-then-remove, which is rejected. The reverse order, {"op":"remove","path":"password"} followed by {"op":"add","path":"password","value":"..."}, clears the flag again and succeeds, so the explicit remove is silently dropped instead of rejected.

That falls out of replace being remove plus add and I am not asking to change it, but the rule is really "a remove is rejected only when it is the last password operation in the request", which is worth stating in the javadoc here and pinning with a test.

this.password = null;
this.passwordRemoved = true;
}

/**
* Returns {@code true} if the password was removed and no new one was staged after that.
*/
public boolean isPasswordRemoved() {
return passwordRemoved;
}

public String getPassword() {
return password;
}

@Override
public void setUsername(String username) {
setSingleAttribute(UserModel.USERNAME, username);
Expand Down
Loading
0