Search code examples
restintershop

How to removing response header with a RestFilter


Is it possible to remove response headers with a RestFilter? Looking at this cookbook you would say it should be possible. However, the filter is only called when the request is incoming, before the call to the resource class. I was expecting to have a hook where I can modify the response headers before sending it back to the client.

i had a look at CORSFilter as an example, but it only sets headers, not remove them.

To be more specific, I want to remove the WWW-Authenticate header that is set by the Auth provider when the session has expired. This header causes a popup in the browser (chrome) that is undesirable.


Solution

  • what you need is a javax.ws.rs.container.ContainerRequestFilter. In jax-rs such filters can be registered in a javax.ws.rs.core.Application. The application used in ICM is com.intershop.component.rest.internal.application.DefaultRestApplication which can be adapted using an com.intershop.component.rest.internal.application.ApplicationClassesProvider that can be registered using a Set-Binding.

    So you could create a Guice-Module and your filter:

    public class MyRestModule extends AbstractModule
    {
        @Override
        protected void configure()
        {
            Multibinder<ApplicationClassesProvider> binder = Multibinder.newSetBinder(binder(),
                            ApplicationClassesProvider.class);
                        binder.addBinding().toInstance(c->c.accept(MyResponseFilter.class));
        }
    }
    
    public class MyResponseFilter extends ContainerRequestFilter
    {
        @Override
        public void filter(ContainerRequestContext request, ContainerResponseContext response)
        {
            response.getHeaders().remove("WWW-Authenticate");
        }
    }
    

    Please note that this filter will be applied to all requests, so please make sure you remove headers only for requests you really care about.