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
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
package org.keycloak.json;

import org.keycloak.util.JsonSerialization;

import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;

Expand All @@ -9,7 +11,7 @@
*/
public final class Jackson2RawJsonValueSupport implements RawJsonValueSupport {

private static final ObjectMapper MAPPER = new ObjectMapper();
private static final ObjectMapper MAPPER = JsonSerialization.plainMapper;

private static JsonNode toNode(Object value) {
if (value instanceof JsonNode) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -524,6 +524,7 @@ public void setOAuth2DeviceCodeLifespan(Integer oauth2DeviceCodeLifespan) {
this.oauth2DeviceCodeLifespan = oauth2DeviceCodeLifespan;
}

@JsonProperty("oauth2DeviceCodeLifespan")
@Schema(name = "oauth2DeviceCodeLifespan")
public Integer getOAuth2DeviceCodeLifespan() {
return oauth2DeviceCodeLifespan;
Expand All @@ -533,6 +534,7 @@ public void setOAuth2DevicePollingInterval(Integer oauth2DevicePollingInterval)
this.oauth2DevicePollingInterval = oauth2DevicePollingInterval;
}

@JsonProperty("oauth2DevicePollingInterval")
@Schema(name = "oauth2DevicePollingInterval")
public Integer getOAuth2DevicePollingInterval() {
return oauth2DevicePollingInterval;
Expand Down Expand Up @@ -1331,6 +1333,19 @@ public void setWebAuthnPolicyPasswordlessMediation(String webAuthnPolicyPassword

// Client Policies/Profiles

// The public getters are needed for the reflection-free serializers generated by Quarkus (feature http-optimized-serializers),
// which skip non-public fields that do not have a getter

@JsonProperty("clientProfiles")
public RawJsonValue getClientProfiles() {
return clientProfiles;
}

@JsonProperty("clientPolicies")
public RawJsonValue getClientPolicies() {
return clientPolicies;
}

@JsonIgnore
public ClientProfilesRepresentation getParsedClientProfiles() {
try {
Expand Down
8 changes: 3 additions & 5 deletions core/src/main/java/org/keycloak/sdjwt/SdJwtUtils.java
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,7 @@
import org.keycloak.common.VerificationException;
import org.keycloak.common.util.Base64Url;
import org.keycloak.jose.jws.crypto.HashUtils;
import org.keycloak.util.JsonSerialization;

import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.core.JsonProcessingException;
Expand All @@ -39,7 +40,7 @@
*/
public class SdJwtUtils {

public static final ObjectMapper mapper = new ObjectMapper();
public static final ObjectMapper mapper = JsonSerialization.plainMapper;
private static final SecureRandom RANDOM = new SecureRandom();

public static String encodeNoPad(byte[] bytes) {
Expand Down Expand Up @@ -125,13 +126,10 @@ public static JsonNode deepClone(JsonNode node) {
static ArraySpacedPrettyPrinter arraySpacedPrettyPrinter = new ArraySpacedPrettyPrinter();

static class ArraySpacedPrettyPrinter extends MinimalPrettyPrinter {
final ObjectMapper prettyPrinObjectMapper;
final ObjectWriter writer;

public ArraySpacedPrettyPrinter() {
prettyPrinObjectMapper = new ObjectMapper();
prettyPrinObjectMapper.setDefaultPrettyPrinter(this);
writer = prettyPrinObjectMapper.writer(this);
writer = JsonSerialization.plainMapper.writer(this);
}

@Override
Expand Down
27 changes: 27 additions & 0 deletions core/src/main/java/org/keycloak/util/JsonSerialization.java
Original file line number Diff line number Diff line change
Expand Up @@ -38,9 +38,36 @@
* @version $Revision: 1 $
*/
public class JsonSerialization {
/**
* The mapper with the Keycloak defaults: no null values are written, empty beans are allowed and the
* JDK 8 and Java time modules are registered.
* <p>
* Shared and must not be reconfigured.
*/
public static final ObjectMapper mapper = createObjectMapperWithDefaults();

/**
* A mapper with indented output that, like {@link #mapper}, does not write null values and allows empty beans.
* Unlike {@link #mapper} it does not register the JDK 8 and Java time modules.
* <p>
* Shared and must not be reconfigured.
*/
public static final ObjectMapper prettyMapper = createPrettyObjectMapperWithDefaults();

/**
* An {@link ObjectMapper} with the plain Jackson defaults, and no Keycloak specific configuration or modules.
* <p>
* Use this instead of creating a new {@code ObjectMapper} when the exact Jackson default behavior is required,
* for example when the serialized form is hashed or signed, or when {@link #mapper} would change the result by
* omitting null values. Prefer {@link #mapper} otherwise.
* <p>
* Shared and must not be reconfigured, as that would affect every other user. To derive a variation use
* {@link ObjectMapper#writer(com.fasterxml.jackson.core.PrettyPrinter)}, {@link ObjectMapper#readerFor(Class)},
* {@link ObjectMapper#writer(SerializationFeature)} or {@link ObjectMapper#copy()}. If a different configuration
* is needed, create a dedicated mapper instead.
*/
public static final ObjectMapper plainMapper = new ObjectMapper();

public static ObjectMapper createObjectMapperWithDefaults() {
ObjectMapper mapper = new ObjectMapper();
mapper.registerModule(new Jdk8Module());
Expand Down
25 changes: 25 additions & 0 deletions docs/documentation/upgrading/topics/changes/changes-27_0_0.adoc
Original file line number Diff line number Diff line change
Expand Up @@ -789,6 +789,31 @@ As a workaround, use the default value of a property that is not defined, for ex
This did not work before, as the `$` prevented the placeholder from being closed.
It only works as long as the property is not defined.

=== REST layer uses the Quarkus managed `ObjectMapper`

The Admin REST API and the other REST endpoints now use the `ObjectMapper` that is managed by Quarkus, instead of one created by {project_name}.
{project_name} applies its own configuration on top of it.

==== JSON properties of custom representations with the `http-optimized-serializers` feature

When the preview feature `http-optimized-serializers` is enabled, {project_name} uses serializers that Quarkus generates at build time instead of reflection.
These generated serializers are created for every class that a REST endpoint accepts or returns, including the representations of custom extensions.
They derive the property name from the getter name by lowercasing only the first character.
Jackson without this feature lowercases all leading uppercase characters.

As a result, a getter that starts with two or more consecutive uppercase characters is serialized under a different name.
For example, `getOAuth2DeviceCodeLifespan()` is serialized as `oAuth2DeviceCodeLifespan` instead of `oauth2DeviceCodeLifespan`, and `getOIDCRequest()` as `oIDCRequest` instead of `oidcrequest`.
Clients that deserialize with the standard names then fail with an unrecognized field error.

{project_name} sets the names explicitly on its own representations, so the Admin REST API is not affected.
Custom extensions that provide an endpoint with their own representation, and that enable this feature, must do the same for such getters.
Add `@JsonProperty("<name>")` with the intended name to the getter.
Representations whose getters start with a single uppercase character followed by a lowercase character, such as `getName()`, are not affected.

The generated serializers also skip a property that is declared as a non-public field annotated with `@JsonProperty` but has no public getter.
The property is then missing from the response without any error, and clients see `null` for it.
Add a public getter for such fields, annotated with `@JsonProperty` when the JSON name differs from the getter-derived name.

=== Client ID Metadata Document executor verifies the back-channel URLs of the client metadata
// https://github.com/keycloak/keycloak/issues/55378

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -31,9 +31,9 @@
import org.keycloak.models.RealmModel;
import org.keycloak.representations.idm.RealmRepresentation;
import org.keycloak.services.ServicesLogger;
import org.keycloak.services.util.ObjectMapperResolver;
import org.keycloak.util.JsonSerialization;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.ObjectWriter;
import com.fasterxml.jackson.databind.SerializationFeature;
import org.jboss.logging.Logger;

Expand Down Expand Up @@ -95,16 +95,15 @@ private void exportRealm(KeycloakSession session, final String realmName) throws
public void close() {
}

private ObjectMapper getObjectMapper() {
ObjectMapper streamSerializer = ObjectMapperResolver.createStreamSerializer();
streamSerializer.configure(SerializationFeature.FAIL_ON_EMPTY_BEANS, false);
streamSerializer.enable(SerializationFeature.INDENT_OUTPUT);
return streamSerializer;
private ObjectWriter getObjectWriter() {
// use the same mapper as SingleFileImportProvider so that the file can always be read back,
// derive from the shared mapper, which must not be reconfigured
return JsonSerialization.mapper.writer(SerializationFeature.INDENT_OUTPUT);
}

private void writeToFile(Object reps) throws IOException {
try (FileOutputStream stream = new FileOutputStream(this.file)) {
getObjectMapper().writeValue(stream, reps);
getObjectWriter().writeValue(stream, reps);
}
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@
import org.keycloak.config.DatabaseOptions;
import org.keycloak.config.Option;
import org.keycloak.jose.jws.crypto.HashUtils;
import org.keycloak.util.JsonSerialization;

import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.core.type.TypeReference;
Expand Down Expand Up @@ -78,7 +79,8 @@ public static void addUnsupportedDatabaseChanges(Map<String, String> metadata) {
Set<ChangeSet> changeSets = new HashSet<>();
Set<Migration> migrations = new HashSet<>();

ObjectMapper objectMapper = new ObjectMapper();
// plain defaults are required as the serialized form is hashed
ObjectMapper objectMapper = JsonSerialization.plainMapper;
while(resources.hasMoreElements()) {
URL url = resources.nextElement();
try (InputStream inputStream = url.openStream()) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,9 @@
import org.keycloak.services.DefaultKeycloakSessionFactory;
import org.keycloak.theme.ClasspathThemeProviderFactory;

import com.fasterxml.jackson.databind.ObjectMapper;
import io.quarkus.arc.Arc;

public final class QuarkusKeycloakSessionFactory extends DefaultKeycloakSessionFactory {

public QuarkusKeycloakSessionFactory(
Expand Down Expand Up @@ -74,6 +77,14 @@ private ProviderFactory lookupProviderFactory(Class<? extends ProviderFactory> f
return factory;
}

/**
* Uses the mapper managed by Quarkus, which is created, with all customizers applied, on first lookup.
*/
@Override
public ObjectMapper getObjectMapper() {
return Arc.container().instance(ObjectMapper.class).get();
}

@Override
public KeycloakSession create() {
return new QuarkusKeycloakSession(this);
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,50 @@
/*
* 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.quarkus.runtime.integration.jaxrs;

import jakarta.inject.Singleton;

import org.keycloak.services.DefaultKeycloakSessionFactory;

import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;
import io.quarkus.jackson.ObjectMapperCustomizer;

/**
* Applies the Keycloak specific configuration to the {@link ObjectMapper} managed by Quarkus.
* <p>
* Using the Quarkus managed mapper allows {@code quarkus.jackson.*} properties to be used to work around
* serialization or deserialization issues. Settings that change the shape of the JSON, such as
* {@code quarkus.jackson.property-naming-strategy}, are not expected to be used. The REST API contract, including the
* generated OpenAPI documentation, is defined with the default camel case property names, so changing them breaks
* clients.
*/
@Singleton
public class KeycloakObjectMapperCustomizer implements ObjectMapperCustomizer {

@Override
public void customize(ObjectMapper mapper) {
// restore the plain Jackson defaults that Quarkus changes
mapper.enable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES);
mapper.enable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS);
Comment thread
vmuzikar marked this conversation as resolved.
Resolved

DefaultKeycloakSessionFactory.configureObjectMapper(mapper);
}

}

This file was deleted.

Original file line number Diff line number Diff line change
Expand Up @@ -17,13 +17,12 @@

package org.keycloak.quarkus.runtime.services;

import java.io.IOException;
import java.util.Objects;

import org.keycloak.representations.idm.OAuth2ErrorRepresentation;
import org.keycloak.services.util.ObjectMapperResolver;
import org.keycloak.util.JsonSerialization;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import io.vertx.core.Handler;
import io.vertx.ext.web.RoutingContext;
import org.jboss.logging.Logger;
Expand All @@ -36,7 +35,6 @@
*/
public class RejectNonNormalizedPathFilter implements Handler<RoutingContext> {
private static final Logger LOGGER = Logger.getLogger(RejectNonNormalizedPathFilter.class);
private final ObjectMapper MAPPER = ObjectMapperResolver.createStreamSerializer();

@Override
public void handle(RoutingContext routingContext) {
Expand All @@ -46,8 +44,8 @@ public void handle(RoutingContext routingContext) {
routingContext.response().headers().add("Content-Type", "application/json; charset=UTF-8");
String jsonString;
try {
jsonString = MAPPER.writeValueAsString(error);
} catch (JsonProcessingException e) {
jsonString = JsonSerialization.writeValueAsString(error);
} catch (IOException e) {
jsonString = "";
}
routingContext.response().setStatusCode(400).end(jsonString);
Expand All @@ -61,8 +59,8 @@ public void handle(RoutingContext routingContext) {
routingContext.response().headers().add("Content-Type", "application/json; charset=UTF-8");
String jsonString;
try {
jsonString = MAPPER.writeValueAsString(error);
} catch (JsonProcessingException e) {
jsonString = JsonSerialization.writeValueAsString(error);
} catch (IOException e) {
jsonString = "";
}
routingContext.response().setStatusCode(400).end(jsonString);
Expand Down
Loading
Loading