eBook – Guide Spring Cloud – NPI EA (cat=Spring Cloud)
announcement - icon

Let's get started with a Microservice Architecture with Spring Cloud:

>> Join Pro and download the eBook

eBook – Mockito – NPI EA (tag = Mockito)
announcement - icon

Mocking is an essential part of unit testing, and the Mockito library makes it easy to write clean and intuitive unit tests for your Java code.

Get started with mocking and improve your application tests using our Mockito guide:

Download the eBook

eBook – Java Concurrency – NPI EA (cat=Java Concurrency)
announcement - icon

Handling concurrency in an application can be a tricky process with many potential pitfalls. A solid grasp of the fundamentals will go a long way to help minimize these issues.

Get started with understanding multi-threaded applications with our Java Concurrency guide:

>> Download the eBook

eBook – Reactive – NPI EA (cat=Reactive)
announcement - icon

Spring 5 added support for reactive programming with the Spring WebFlux module, which has been improved upon ever since. Get started with the Reactor project basics and reactive programming in Spring Boot:

>> Join Pro and download the eBook

eBook – Java Streams – NPI EA (cat=Java Streams)
announcement - icon

Since its introduction in Java 8, the Stream API has become a staple of Java development. The basic operations like iterating, filtering, mapping sequences of elements are deceptively simple to use.

But these can also be overused and fall into some common pitfalls.

To get a better understanding on how Streams work and how to combine them with other language features, check out our guide to Java Streams:

>> Join Pro and download the eBook

eBook – Jackson – NPI EA (cat=Jackson)
announcement - icon

Do JSON right with Jackson

Download the E-book

eBook – HTTP Client – NPI EA (cat=Http Client-Side)
announcement - icon

Get the most out of the Apache HTTP Client

Download the E-book

eBook – Maven – NPI EA (cat = Maven)
announcement - icon

Get Started with Apache Maven:

Download the E-book

eBook – Persistence – NPI EA (cat=Persistence)
announcement - icon

Working on getting your persistence layer right with Spring?

Explore the eBook

eBook – RwS – NPI EA (cat=Spring MVC)
announcement - icon

Building a REST API with Spring?

Download the E-book

Course – LS – NPI EA (cat=Jackson)
announcement - icon

Get started with Spring and Spring Boot, through the Learn Spring course:

>> LEARN SPRING
Course – RWSB – NPI EA (cat=REST)
announcement - icon

Explore Spring Boot 3 and Spring 6 in-depth through building a full REST API with the framework:

>> The New “REST With Spring Boot”

Course – LSS – NPI EA (cat=Spring Security)
announcement - icon

Yes, Spring Security can be complex, from the more advanced functionality within the Core to the deep OAuth support in the framework.

I built the security material as two full courses - Core and OAuth, to get practical with these more complex scenarios. We explore when and how to use each feature and code through it on the backing project.

You can explore the course here:

>> Learn Spring Security

Course – LSD – NPI EA (tag=Spring Data JPA)
announcement - icon

Spring Data JPA is a great way to handle the complexity of JPA with the powerful simplicity of Spring Boot.

Get started with Spring Data JPA through the guided reference course:

>> CHECK OUT THE COURSE

Partner – Moderne – NPI EA (cat=Spring Boot)
announcement - icon

Refactor Java code safely — and automatically — with OpenRewrite.

Refactoring big codebases by hand is slow, risky, and easy to put off. That’s where OpenRewrite comes in. The open-source framework for large-scale, automated code transformations helps teams modernize safely and consistently.

Each month, the creators and maintainers of OpenRewrite at Moderne run live, hands-on training sessions — one for newcomers and one for experienced users. You’ll see how recipes work, how to apply them across projects, and how to modernize code with confidence.

Join the next session, bring your questions, and learn how to automate the kind of work that usually eats your sprint time.

Course – LJB – NPI EA (cat = Core Java)
announcement - icon

Code your way through and build up a solid, practical foundation of Java:

>> Learn Java Basics

1. Introduction

Keycloak is an open-source Identity and Access Management (IAM) solution focusing on modern applications and services. When users authenticate through Keycloak, tokens issued by the server contain important information about the authenticated user and the client to which tokens were issued.

Keycloak’s tokens contain some default attributes, such as iss (issuer), exp (expiration time), sub (subject), and aud (audience). But many times, these aren’t enough, and we might need to add some extra information to the tokens. In this situation, we use a protocol mapper.

In this tutorial, we’ll show how to add a custom protocol mapper to the Keycloak authorization server.

2. Protocol Mapper

A Keycloak token is just a JSON object that contains a set of claims and is usually digitally signed. Let’s check out an example of a token’s payload and its collection of standardized claims:

{
  "exp": 1680679982,
  "iat": 1680679682,
  "jti": "bebf7b2c-f813-47be-ad63-0ca6323bba19",
  "iss": "http://192.168.198.128:8085/auth/realms/baeldung",
  "aud": "account",
  "sub": "648b0687-c002-441d-b797-0003b30168ed",
  "typ": "Bearer",
  "azp": "client-app",
  "acr": "1",
  ...
  "scope": "email profile",
  "clientId": "client-app",
  "clientHost": "192.168.198.1",
  "email_verified": false,
  "preferred_username": "service-account-client-app",
  "clientAddress": "192.168.198.1"
}

Protocol mappers map items such as an email address to a specific claim in the identity and access token. We can customize the claims in the token with specific details by adding protocol mappers to the clients.

3. Setting Up a Keycloak Server

In this tutorial, we’ll be using the Keycloak standalone version. We’ve already covered how to set up a Keycloak server, so we won’t go into details on how it’s done here.

Let’s add a new realm called baeldung and a new client called client-app to our Keycloak instance:

new client

We’ll leave all the defaults except the Client authentication and Service accounts roles fields:

fields

The Service accounts roles field enables support of the Client Credentials Grant for this client.

4. Custom Protocol Mapper Implementation

Now that we’ve set up our Keycloak server, we’ll create a custom protocol mapper and configure it in the Keycloak server.

4.1. Dependencies

Our custom protocol mapper is a regular Maven project that creates a JAR file.

Let’s start by declaring the keycloak-core, keycloak-server-spi, keycloak-server-spi-private, and keycloak-services dependencies in our pom.xml:

<dependency>
    <groupId>org.keycloak</groupId>
    <artifactId>keycloak-core</artifactId>
    <scope>provided</scope>
    <version>21.0.1</version>
</dependency>
<dependency>
    <groupId>org.keycloak</groupId>
    <artifactId>keycloak-server-spi</artifactId>
    <scope>provided</scope>
    <version>21.0.1</version>
</dependency>
<dependency>
    <groupId>org.keycloak</groupId>
    <artifactId>keycloak-server-spi-private</artifactId>
    <scope>provided</scope>
    <version>21.0.1</version>
</dependency>
<dependency>
    <groupId>org.keycloak</groupId>
    <artifactId>keycloak-services</artifactId>
    <scope>provided</scope>
    <version>21.0.1</version>
</dependency>

4.2. Extending the AbstractOIDCProtocolMapper Class

Now let’s create our protocol mapper. For that, we extend the AbstractOIDCProtocolMapper class and implement all abstract methods:

public class CustomProtocolMapper extends AbstractOIDCProtocolMapper implements OIDCAccessTokenMapper,
  OIDCIDTokenMapper, UserInfoTokenMapper {

    public static final String PROVIDER_ID = "custom-protocol-mapper";

    private static final List<ProviderConfigProperty> configProperties = new ArrayList<>();

    static {
        OIDCAttributeMapperHelper.addTokenClaimNameConfig(configProperties);
        OIDCAttributeMapperHelper.addIncludeInTokensConfig(configProperties, CustomProtocolMapper.class);
    }

    @Override
    public String getDisplayCategory() {
        return "Token Mapper";
    }

    @Override
    public String getDisplayType() {
        return "Custom Token Mapper";
    }

    @Override
    public String getHelpText() {
        return "Adds a Baeldung text to the claim";
    }

    @Override
    public List<ProviderConfigProperty> getConfigProperties() {
        return configProperties;
    }

    @Override
    public String getId() {
        return PROVIDER_ID;
    }

    @Override
    protected void setClaim(IDToken token, ProtocolMapperModel mappingModel,
      UserSessionModel userSession, KeycloakSession keycloakSession,
      ClientSessionContext clientSessionCtx) {
        OIDCAttributeMapperHelper.mapClaim(token, mappingModel, "Baeldung");
    }
}

We’ve chosen “custom-protocol-mapper” for our provider ID, which is the ID of the token mapper. We need this ID to configure the protocol mapper in our Keycloak server.

The main method is setClaim(). It adds our data to the token. Our setClaim() implementation simply adds a Baeldung text to the token.

The getDisplayType() and getHelpText() methods are for the admin console. The getDisplayType() method defines the text that will be shown in the admin console when listing the protocol mapper. The getHelpText() method is the tooltip text shown when we pick the protocol mapper.

4.3. Bringing It All Together

We mustn’t forget to create a service definition file and add it to our project. This file should be named org.keycloak.protocol.ProtocolMapper and placed in the META-INF/services directory of our final JAR. Also, the content of the file is the fully qualified class name of the custom protocol mapper implementation:

com.baeldung.auth.provider.mapper.CustomProtocolMapper

The directory structure is depicted below:

directory structure

Now, the project is ready to run. First, we create a JAR file using the Maven install command:

mvn clean install

Next, we deploy the JAR file to Keycloak by adding it to the providers directory of Keycloak. After that, we must restart the server to update the server’s provider registry with the implementation from our JAR file:

$ bin/kc.sh start-dev

As we can see in the console output, Keycloak registers our custom protocol mapper:

Updating the configuration and installing your custom providers, if any. Please wait.
2023-04-05 14:55:42,588 WARN  [org.keycloak.services] (build-108) KC-SERVICES0047: custom-protocol-mapper (com.baeldung.auth.provider.CustomProtocolMapper) is implementing the internal SPI protocol-mapper.

Finally, if we go to the Provider info page, available at Keycloak’s admin console, we’ll see our custom-protocol-mapper:

custom protocol mapper

Now, we can configure the server to use our custom protocol mapper.

4.4. Configuring a Client

In Keycloak, we can add custom claims using the admin panel. For that, we need to go to our client on the admin console. Recall that earlier, we’d created a client, client-app. After that, we navigate to the Client scopes tab:

client scopes

Now, let’s click on client-app-dedicated and go to its Add mapper By configuration to create a new mapping:

new mapping

Here, we need to enter the Mapper type for our custom mapper. We’ll type “Custom Token Mapper“, which is the value we used for the getDisplayType() method in our CustomProtocolMapper class:

CustomProtocolMapper

Next, we give a Name to the mapper and save it. Then, when we go back to the client-app-dedicated, we’ll see the new mapping in the list:

mapper

Now, we’re ready to test our protocol mapper.

5. Testing

Let’s get an access token for the client using the Client Credential grant type:

curl --location --request POST 'http://server-ip:server-port/auth/realms/baeldung/protocol/openid-connect/token' \
--header 'Content-Type: application/x-www-form-urlencoded' \
--data-urlencode 'client_id=client-app' \
--data-urlencode 'client_secret=<client-secret>' \
--data-urlencode 'grant_type=client_credentials'

If we obtain an access token and decode it using jwt.io, we find the test claim in the token’s body:

{
  "exp": 1680679982,
  "iat": 1680679682,
  ...
  "email_verified": false,
  "test": "Baeldung",
  "preferred_username": "service-account-client-app",
  "clientAddress": "192.168.198.1"
}

As we can see, the value of the test claim is Baeldung.

6. Conclusion

In this article, we implemented a custom protocol mapper in the Keycloak server. In general, a token is a set of attributes or claims. Protocol mappers will provide the option to add custom claims to a token.

The code backing this article is available on GitHub. Once you're logged in as a Baeldung Pro Member, start learning and coding on the project.
Baeldung Pro – NPI EA (cat = Baeldung)
announcement - icon

Baeldung Pro comes with both absolutely No-Ads as well as finally with Dark Mode, for a clean learning experience:

>> Explore a clean Baeldung

Once the early-adopter seats are all used, the price will go up and stay at $33/year.

eBook – HTTP Client – NPI EA (cat=HTTP Client-Side)
announcement - icon

The Apache HTTP Client is a very robust library, suitable for both simple and advanced use cases when testing HTTP endpoints. Check out our guide covering basic request and response handling, as well as security, cookies, timeouts, and more:

>> Download the eBook

eBook – Java Concurrency – NPI EA (cat=Java Concurrency)
announcement - icon

Handling concurrency in an application can be a tricky process with many potential pitfalls. A solid grasp of the fundamentals will go a long way to help minimize these issues.

Get started with understanding multi-threaded applications with our Java Concurrency guide:

>> Download the eBook

eBook – Java Streams – NPI EA (cat=Java Streams)
announcement - icon

Since its introduction in Java 8, the Stream API has become a staple of Java development. The basic operations like iterating, filtering, mapping sequences of elements are deceptively simple to use.

But these can also be overused and fall into some common pitfalls.

To get a better understanding on how Streams work and how to combine them with other language features, check out our guide to Java Streams:

>> Join Pro and download the eBook

eBook – Persistence – NPI EA (cat=Persistence)
announcement - icon

Working on getting your persistence layer right with Spring?

Explore the eBook

Course – LS – NPI EA (cat=REST)

announcement - icon

Get started with Spring Boot and with core Spring, through the Learn Spring course:

>> CHECK OUT THE COURSE

Partner – Moderne – NPI EA (tag=Refactoring)
announcement - icon

Modern Java teams move fast — but codebases don’t always keep up. Frameworks change, dependencies drift, and tech debt builds until it starts to drag on delivery. OpenRewrite was built to fix that: an open-source refactoring engine that automates repetitive code changes while keeping developer intent intact.

The monthly training series, led by the creators and maintainers of OpenRewrite at Moderne, walks through real-world migrations and modernization patterns. Whether you’re new to recipes or ready to write your own, you’ll learn practical ways to refactor safely and at scale.

If you’ve ever wished refactoring felt as natural — and as fast — as writing code, this is a good place to start.

Course – LSS – NPI (cat=Security/Spring Security)
announcement - icon

I just announced the new Learn Spring Security course, including the full material focused on the new OAuth2 stack in Spring Security:

>> CHECK OUT THE COURSE

eBook Jackson – NPI EA – 3 (cat = Jackson)
2 Comments
Oldest
Newest
Inline Feedbacks
View all comments