OIDC client - Change preferred_username in token


Is there a possibility to overwrite the “preferred_username” of an OIDC client that seems to be auto generated by Keycloak? If I have a client with e.g. name “something”, by getting the token there I can see the “preferred_username” which has the value “service-account-something”.

Can someone point me to a solution? Is there a way to overwrite it e.g. by mapper or by implementing a SPI?



You can do this using a JavaScript mapper according to this documentation:

The JS code:

token.setOtherClaims("preferred_username", "this is the new value");

(or just by returning the new value in the script code and configuring the mapper to fill the preferred_username claim when you configure the mapper in the KC admin console)


That doesn’t sound too difficult. I’ll try it out shortly. Thank you very much for the hint!

Did you find the solution to the above issue?

I am also using the Keycloak for one of our product. And we are using the client credentials grant flow to get the access token for service to service communication. And the issue is, preffered_username is coming as “service_account_test.” Our product also has a service account(e.g username_service) that needs to be embedded into the token, so that we have the activity logs for that service account.

So my question is,

  1. Am I using the correct grant flow for the use case.
  2. Can we embed something from the request into the token. Does the token endpoint takes additional attributes in the payload that can be added to the token?