Accessing grant type in protocol mapper

Hi all,

I have a requirement to trigger a custom mapper based on the grant_type of the request.

Say I have a client configured with standard flow for user to authenticate with authorisation code flow but also for client credentials grant (client I’d and secret) this client has a series of scopes assigned with a custom mapper to map claims from an external source and these are primarily for the web flow. I also have a custom mapper assigned at the client level. I want this mapper to only map claims when the grant_type is client credentials grant so I don’t end up with claims from the client in the users claim. In the client Authenticators, I can see that the grant type is normally posted in the form data. Iv tried stashing this grant type in client notes, user session notes and session attributes and I don’t seem to be able to pull this through in the protocol mapper.

So I guess a couple of questions if I may.

  1. does this approach sound reasonable to achieve the goal of triggering different mappers depending on grant type ? If not, any suggestions on alternative approaches ?

  2. is there a more efficient way of grabbing the grant type from with a protocol mapper ?

I pass thanks in advance for any and all input.


In a Javascript based mapper, does this work?
(see AuthenticationSessionModel (Keycloak Docs Distribution 20.0.3 API))

If that does not work, I would use a second client fur the client credentials grant use case.

Hi @mbonn,

Thanks for the response. Il have to give this a try.

I had been thinking over the weekend as to whether I could do without stashing the grant_type at all during the client authentication as that would mean having to keep some ever so slightly modified versions of those client authenticators under my remit. To me, it just didnt make sense.

I trawled through the keycloak sourcecode and can see grant_type is referenced in numerous places, but in the most part its obtained from the request itself. With a little bit of trace logging on i could see a keycloak event posted for the client login which had the “CLIENT_LOGIN” event type and this sparked a bit of curiosity.

In the TokenEndpoint class there is a method to check the grant type (checkGrantType). It suggests that when the grantType is equal to OAuth2Constants.CLIENT_CREDENTIALS (“client_credentials”) then the event type is indeed “CLIENT_LOGIN”. I can get the authMethod from the userSessionModel in the protocol mapper with ease.

Dare I infer that the authMethod of “client_auth” is indeed indicative of client_credentials grant? It certainly seems to suggest so. Id love to say i have a proven track record when I infer things, but unfortunately I don’t :slight_smile: