How do protocol mappers work in Keycloak?

I am trying out an example to add user attributes to the claim. I am following the example here. I am trying to access the claim in a filter and am unsuccessful.

I would want to understand how the protocol mappers work behind the scenes, namely how and in which order are those claims from that protocol added into the token.

Answer

In Keycloak, the function of the protocol mappers is to add additional claims to a JWT besides those that are added by default by Keyloack.

Different Protocol Mapper will have different options, but for most of them you can chose to add the claims that those mappers will produce into the:

  • ID Token;
  • Access Token;
  • UserInfo;

I would want to understand how the protocol mappers work behind the
scenes.

Roughly, what will happen is the following the JWT is basically an encoded JSON Object based on a specific standard, Keycloak creates that object with the Registered claims (e.g., Issuer, Subject and so on), and then it will apply the custom claims (i.e., protocol Mappers) into that temporary object by the Priority Order that you have defined for that given protocol Mapper.

The end result (i.e., the token) will be a JWT with the default claims, and with the claims added with the protocol mappers.