'Change the preferred_username in token for client credential grant flow

I am 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, preferred_username is returned as service_account_<clientname>. Our product also has a service account(e.g _service) that needs to be embedded into the token, so that we have the activity logs against that service account.

So my questions are:

  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 take additional attributes in the payload that can be added to the token?


Solution 1:[1]

So my question is,

  1. Am I using the correct grant flow for the use case.

According to OAuth 2.0 Client Credentials Grant

The Client Credentials grant type is used by clients to obtain an access token outside of the context of a user.

This is typically used by clients to access resources about themselves rather than to access a user's resources.

And according to your requirement:

to get the access token for service to service communication

Without any more context I would say that yes, you are using the appropriate flow.

  1. Can we embed something from the request into the token. Does the token endpoint take additional attributes in the payload that can be added to the token?

Depending upon what you want to add to the token you can simply use Protocol Mappers.

Some mappers already come with predefined claims to be injected into the token, one can also make its own protocol mappers by extending the Keycloak code or by exploiting the script mapper functionality (more details in the official documentation).

The other approach is to use keycloak UMA flow pushing claims capabilities. In which you put your claims into the request to the token endpoint and get in return (if successfully authenticated) a token with those claims injected into it.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1