How to set an empty list as a claim in Keycloak token after custom mapper

32 views Asked by At

I'm currently using Keycloak version 18 for multiple applications, and I've encountered a problem during the migration of another application to Keycloak. In my setup, users in Keycloak have an attribute called "roles" which contains their Active Directory (AD) groups.

To meet a specific requirement, Keycloak should only include groups relevant to the application and its environment in the token. To achieve this, I've implemented a Filtered User Attribute Mapper, which filters the groups based on a specific schema using a regex. Unfortunately, I am not able to share the exact code of the custom mapper.

However, I've noticed that if the regex doesn't match any groups, and an empty list is expected for the token claim, Keycloak doesn't set the claim in the token. This causes issues for the application, as the expected claim is missing in the token, leading to errors.

Additionally, it's important to note that at the end of the mapping process, the method OIDCAttributeMapperHelper.mapClaim(IDToken token, ProtocolMapperModel mappingModel, Object attributeValue) is called to complete the mapping process. The variable attributeValue would in my case be the empty list. See also the OIDCAttributeMapperHelper class in Github.

I've looked into the GitHub issue related to this problem and found it in the Keycloak code.

public static Object mapAttributeValue(ProtocolMapperModel mappingModel, Object attributeValue) {
        if (attributeValue == null) return null;

        if (attributeValue instanceof Collection) {
            Collection<?> valueAsList = (Collection<?>) attributeValue;
            if (valueAsList.isEmpty()) return null;

Is there any workaround or configuration tweak in Keycloak that allows setting an empty list as a claim for the AD groups in the token?

I attempted to extend the OIDCAttributeMapperHelper to address the issue. Despite my efforts, I couldn't find a satisfactory solution.

0

There are 0 answers