How to break infinite redirect loop on Keycloak Authorization Code Flow error (before token exchange)?

709 views
Skip to first unread message

Carlos Eduardo de Melo Rodovalho

unread,
May 20, 2025, 1:43:52 PM5/20/25
to Keycloak User

Hi all,

I'm using Keycloak with the Authorization Code Flow in my PHP application. The flow works like this:

  1. User authenticates on Keycloak.
  2. Keycloak redirects to my app with only the code parameter.
  3. My app exchanges the code for tokens (access_tokenid_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?

Francisco Moura

unread,
May 20, 2025, 3:35:20 PM5/20/25
to Carlos Eduardo de Melo Rodovalho, Keycloak User
Hi Carlos, I would suggest you to use some library to assist you with this.
In the keycloak guides, there is this: https://www.keycloak.org/securing-apps/overview
For example, you could use apache to handle these requirements.
Try not to do it by yourself.
See this talk from spring guys: https://www.youtube.com/watch?v=bH5PxcJzwME

I hope this helps you!

Atenciosamente,
Francisco Moura


--
You received this message because you are subscribed to the Google Groups "Keycloak User" group.
To unsubscribe from this group and stop receiving emails from it, send an email to keycloak-use...@googlegroups.com.
To view this discussion visit https://groups.google.com/d/msgid/keycloak-user/6d9137d3-af44-4a53-a66e-a9afae7b9cfbn%40googlegroups.com.

Carlos Eduardo de Melo Rodovalho

unread,
May 21, 2025, 7:23:26 AM5/21/25
to Keycloak User
Hi Francisco,

it's a legacy application, so I'm quite restricted on libraries I can use, but i'll look it up event to try to understand how they do it. Thanks
Also, thanks for the video, it was very educative.
Reply all
Reply to author
Forward
0 new messages