Run JavaScript code after Keycloak Freemarker Theme successful login

Hi all.

I’m not sure if that what I’m trying to do is a good practice or a secure way to do it.
I was requested to store the First Name of the user in cookies after a successful login using a Keycloak Freemarker Theme.

I was not able to reach a solution yet because I’m not able to run any code after the form post, because Keycloak is responding with a redirect.

Does someone knows how to do such a thing?

Thanks in advance :slight_smile:

Why not just get the First Name from the token?

If you need it to be in a cookie, then you can write javascript on the page that it gets redirected to, take it from the token, and then put it in a cookie.

Hi xgp!! first of all many thanks for your answer…

That sounds good, the thing is that I have no chances to write code within the redirect destination page because it is maintained by a completely different team (at least not in a short-term).

My question was more about doing something within the Keycloak Login Theme itself before the redirection.

Thanks for the additional context. This is just an idea of how I’d proceed with this restriction. Not 100% sure it would work:

You could add a custom RequiredActionProvider that gets run after every login. The evaluateTriggers method would get called every time a user authenticates, and you could add the required action in that method. Then in the requiredActionChallenge method, update the to set a Set-Cookie header with the cookie you want to set (not 100% sure you can set it to a domain that will allow the client to access it), and mark it success so that the user would get redirected to the correct location.

This is where I’d start experimenting. It may be that the redirect would wipe out the Set-Cookie header, so you may have to actually render a page so you could set the cookie that way or in Javascript.

1 Like