Custom authenticator on token exchange

We’re just getting started wih keycloak, and trying to use token exchange to swap between tokens for 2 internal clients on the same keycloak realm (one token just has lower/different claims than the other).
To do this I’ve got the token exchange calling auth/realms/{myrealm}/protocol/openid-connect/token calling with grant type urn:ietf:params:oauth:grant-type:token-exchange, and that is working fine.

What we also need to do is some custom logic just prior to the token exchange occurring - (we make an external GET request), and if the logic is valid, then continue with token exchange. I’ve written a simple custom java authenticator which makes the external request/authenticate logic.

What I can’t work out is how to do add this custom authenticator for a token exchange grant type - is this possible to do so, or is a different approach needed to doing custom logic prior to token exchange?

For flows like direct grant, I can just create and bind to my own direct grant flow which has the custom authenticator. Can we do something similar for token exchange?

Has anyone else extended keycloak with custom logic prior to token exchange occurring?
Many thanks

I don’t 100% understand what you want to achieve…

You want to block user accessing your app when a specific claim is missing?
You can modify the Browser flow and make a role mandatory.

You want to add custom claims to to the token?
Implement an OICD Token transformer.
Have one myself that fetches additional data from our CRM

Our use case is basically that a user will start of with certain base claims (we have a modified browser flow working here), but during the user’s workflow, we need to add or subtract certain claims from the token. For now I have something working via a direct grant token request which has it’s own custom authenticator which calls our CRM, and a few additional token mappers.

I was going down the track of using the token-exchange grant type with a custom authenticator, but couldn’t work out how to make custom authenticator logic even execute when using that grant type. It seemed like exchanging one token for another was a cleaner approach than a request for a new token.

I’ve abandoned that for now as a) token-exchange functionality is still in preview, and b) another direct grant request with some custom logic can give us the token with modified claims that we need, albeit now with 2 different sessions created, so we just remove the previous session.