How to intercept login to keycloak via IDP?

462 views
Skip to first unread message

Maxim Kopeyka

unread,
Mar 8, 2021, 1:15:06 PM3/8/21
to Keycloak Dev
Hi all,

I would like to remove existing user from keycliak db in case he logins in via IDP. I created authenticator and it works fine in case of “first broker login” but it doesn’t trigger in case it’s not first broker login. I tried to add it to browser flow but it doesn’t help.
The main idea to create a new user every time in case user with the same username already exists.

Alvaro Arenas

unread,
Mar 10, 2021, 1:51:26 AM3/10/21
to Keycloak Dev
Hi,

I am not an expert but one way you can achieve this is by creating a custom mapper which you add to you idp.
The mapper has a method called preprocessFederatedIdentity() where you have access to the idp id (or email)

preprocessFederatedIdentity()
* Called to determine what keycloak username and email to use to process the login request from the external IDP.
* It's called before "FirstBrokerLogin" flow, so can be used to map attributes to BrokeredIdentityContext (
* BrokeredIdentityContext.setUserAttribute ),
* which will be available on "Review Profile" page and in authenticators during FirstBrokerLogin flow

You can use that to find your user and delete it. For that there is a method in the KeycloakSession object session.users().removeUser().

I am curious what is the use case to delete the user every time it will log in. It is quite counterintuitive.

I hope it helps,

Alvaro

Maxim Kopeyka

unread,
Mar 11, 2021, 9:32:21 AM3/11/21
to Keycloak Dev
Thanks a lot, it works in this way :)

Ronaldo Hideki Yamada

unread,
Mar 11, 2021, 2:12:21 PM3/11/21
to Keycloak Dev
Hi,

Put your developed authenticator  in post login flow. 

Create a flow, register them on IDP, them KC will call.

Maxim Kopeyka

unread,
Mar 11, 2021, 5:27:21 PM3/11/21
to Keycloak Dev
I tried this solution but keycloak throws error because that authenticator implementations must assume that user is already set in ClientSession as identity provider already set it so deleting of this user causes exception.
Reply all
Reply to author
Forward
0 new messages