Hi all,
I’m using Keycloak with the Authorization Code Flow in my PHP application. The flow works like this:
- User authenticates on Keycloak.
- Keycloak redirects to my app with only the
code
parameter.
- My app exchanges the code for tokens (
access_token
, id_token
, etc.) using the Keycloak token endpoint.
The problem:
If an error occurs after I get the tokens, I can use id_token_hint
to log the user out of Keycloak and redirect them to the login page, which works fine.
But if an error occurs during the code exchange (i.e., after receiving the code but before getting any tokens), I don’t have the id_token
, so I can’t log the user out of Keycloak. If I simply redirect the user back to the Keycloak login page, Keycloak detects the active session and immediately redirects back to my app with a new code, causing an infinite redirect loop.
Question:
What is the proper way to handle errors that happen after receiving the authorization code, but before obtaining the tokens, so I can break this loop and allow the user to try authenticating again?
Any best practices or recommended approaches for this scenario?
You are in an edge case, because if you’re not able to exchange the authorization code for a token, it’s usually due to a misconfiguration in the application.
However, as a way to force the login, you can use the standard prompt=login
[1], which will make the IdP prompt for login again.
[1] Final: OpenID Connect Core 1.0 incorporating errata set 2
2 Likes
Thank you! Forcing the prompt login is exactly what i need!
And yes, I understand that this situation should not happen normally, but as I’m trying to handle every possible error during the flow.
Glad to help! But remember, keep things as simple as possible!
1 Like
Maybe you should revisit what you do in case of such an error by looking at what would cause the error (realistically):
- keycloak crashed → you would need to wait for the restart anyway, so just hint the user to try later
- a network error from your app server to keycloak
→ again, a fatal error
- app/keycloak configuration error → again this would not magically resolve itself
So i think that this error case should be handled on the app side with an auth service is not available, try again later
error message.
1 Like
To bring a little bit more “fun” to this:
I had this “infinite redirect loop” several times in conjunction with either old/invalid cookies and/or the hidden iframe. The latter only when using in JS-based apps with the JS-adapter.
1 Like
Thanks @bpedersen2 . This was a force error, just trying to handle a possible network instability gracefully. Now I understand that I must redirect the user somewhere else, or use prompt=login to stop the loop. I customized Keycloak’s login theme to show custom error messages, so now it works as intended.
A huge thanks to this comunity. Keycloak is a wonderfull tool and it’s been very nice to learn from you guys.
1 Like