How to redirect keyclock to application's page and get token

marcg picture marcg · Sep 8, 2020 · Viewed 10.5k times · Source

I am using keycloak's login and registration page. For login I use:

 keycloak.init({onLoad: 'login-required'}).then(function (authenticated) {
        if (!authenticated) {
           
        } else{

        }

This works fine as I can use the code above to redirect to the application page with token received. However, if the user clicks on registration link and register as a new user, I see browser redirected to :

htttps://localhost/auth/realms/realm1/login-actions/registration?session_code=2TC4xBE5BoFy_Dt7nK8wNDzdLx-8rJmA7l0IjTY1Khk&execution=2e64e3ef-185a-4ca8-a6cc-51c40f9fb7fc&client_id=bizmapp&tab_id=EbayK64spNk

I would like a keycloak callback after registration where I can get the token and redirect the user to the application's original secured page where the user wanted to go to before the login/registration

Answer

otonglet picture otonglet · Sep 9, 2020

In Keycloak administration interface go to "Authentication" then to the "Flows" tab. Select "registration" in the top left drop-down to configure the registration flow. You can then add a "browser Redirect/Refresh" action at the end of the flow.

You can find more information at https://www.keycloak.org/docs/latest/server_admin/index.html#_authentication-flows

Passing tokens as query params is conventionally considered a bad idea since they stay in the browser history and 1° could be stolen if someone else access that browser and 2° are leaked to 3rd party, for instance when you are using stuff like Google Analytics.

You application should be able to detect the user is authenticated from Keycloak SSO cookie (or whatever other mechanism), that I think will be set automatically after the registration. You just have to rely on the Keycloak adapter configured for your application.