Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Keycloak access cookie and/or url query params inside freemarker template

I want to access to some info's inside keycloak freemarker template. There are two approaches I am thinking about. To set url parameters and read them inside freemarker template or to set this info to a cookie and access them inside the template.

I tried already to access url parameters as described here or here. But both are not working. Keycloak data model doesn't provide any getters for current Url.

Is one of those approaches possible? How can I achieve my goal

like image 493
user3287019 Avatar asked May 19 '17 14:05

user3287019


2 Answers

I ran into a similar problem, where I had to access query parameters in my custom keycloak login theme. (using Keycloak version 2.1.0.Final)

There was no query param passed to my login site. But I found out that inside

org.keycloak.forms.login.freemarker.FreeMarkerLoginFormsProvider

you can access the following query parameters:

  • scope
  • response_type
  • redirect_uri
  • state
  • nonce
  • client_id
  • response_mode

That is possible by using

UriInfo uriInfo = session.getContext().getUri();
MultivaluedMap<String, String> queryParameters = uriInfo.getQueryParameters();

You can read the query param redirect_uri like this

String redirectUri = queryParameters.getFirst("redirect_uri")

To pass certain data to your template you must use

attributes.put("keyToData", dataForTemplate);

before your process the template by

freeMarker.processTemplate(attributes, Templates.getTemplate(page), theme);

Then in your template (e.g. template.ftl) you can access the provided data, for instance:

<#if keyToData!false == true> 
    ...
</#if>

Unfortunately I was not able to access custom query parameters passed to my keycloak /auth endpoint inside FreeMarkerLoginFormsProvider.

like image 146
Bernhard Avatar answered Oct 12 '22 13:10

Bernhard


To get query parameters, I used Javascript, because I struggled way too much with free marker

    <script type="text/javascript">
        const urlParams = new URLSearchParams(window.location.search);
        const myParam = urlParams.get('myParam');
    </script>

Hope it'll help someone

like image 37
PestoP Avatar answered Oct 12 '22 14:10

PestoP