'Keycloak token doesn't include mapped user session note on first login

I have created a custom IDP and whenever I login I need to set a User Session Note which is mapped in Keycloak and then added to the access token. The problem I am facing is that this User Session Note is not saved the first time a user logs in. It works the second time, and third and so on, but on the first login the user does not simply get the key/value added to the token.

The login succeeds every time, however it is missing the user session note that I wanted to be mapped on the token.

I'm not sure what the problem is. The IDP is set up to have a custom "First Login Flow" which has Create User If Unique (alternative) and Automatically Set Existing User (alternative). Maybe there is something here that I need to change so that it also includes User Session Notes on token for the first login?



Solution 1:[1]

I found that you need to implement the importNewUser() method in your extension of AbstractIdentityProviderMapper and set your notes on the authenticationSessionModel there.

Inside of the authenticated method, where preprocessFederatedIdentity() is called, Keycloak checks if federatedUser == null. At this point, you are in the state of preprocessing the federated user; it does not yet exist. Keycloak then calls resetFlow() within this if block where it then clears auth notes from the authenticationSessionModel.

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 Adrian Mole