Is it possible to register a filter to process an extra header?

I have an extension that implements EventListenerProvider.

on the method: public void onEvent(Event event) I have no access to the http request, and I need to grap some extra header I’m adding on the request.

Is is possible to register some Web filter to grab the header and put on a thread local so I can grab it there?

regards

What specific request are you looking for? Not every event will have a 1-1 relationship with an HTTP request. If, for example, it’s something that happens in the authentication flow, you could build a custom authenticator that would store the request for you.

I just need it for the admin REST calls events, so I think it will be 1-1 relationship with HTTP. I’m using a service account to call the REST API to have more fine grain control on what can be done and I need to pass header with extra context (real user behind the call, for e.g.). I wanted a simple solution, like @WebFilter or even a JAX-RS PreMatching Filters, but I see no way to register them via an extension. Any suggestion?

I am not familiar with adding filters to the admin resources, but it may be possible. Here or the keycloak-dev mailing list are likely the best places to ask.

Solution is quite simple as in jax-rs we can get the context with:

HttpServletRequest httpServletRequest = ResteasyProviderFactory.getContextData(HttpServletRequest.class);

1 Like

Thanks for sharing the solution.

Great that you found a solution yourself.

I also have an example for this in my keycloak-extension-playground here: keycloak-extension-playground/GlobalRequestResponseFilterResourceProvider.java at master · thomasdarimont/keycloak-extension-playground · GitHub

There are many ways to register the custom filter, in my example I use a RealmResourceProviderFactory that just returns an empty resource. It would really be helpful if Keycloak had something like a BootstrapSpi that would allow you to register callbacks to register things like Request/Response filters or perform other types of server customization.

If you need to process also non API requests, then you could either try to add your filter directly in the KeycloakApplication or create an Undertow filter and propagate additional data via request attributes.

2 Likes

How can I register the filter in the KeycloakApplication? I’m using Keycloak version 23.0.4 and would like to intercept the Authenticator requests… Is it possible to override the KeycloakApplication? Because when I try to override it I get an error from Quarkus about not being able to handle multiple applications. Is there another way to register the filter?

1 Like

We had a similar problem. I found ServerRequestFilter / ServerResponseFilter not being picked up · Issue #25038 · keycloak/keycloak · GitHub which helped to solve it.