6

I'm trying to add a Authorization header to my request as a temporary workaround while we are switching environments. I'm trying to handle it in a interceptor that extends HandlerInterceptorAdapter.

I used the MutableHttpServletRequest class made here in order to be able to add the header to the request, but it doesn't seem like there is any way you can actually modify the returned request in the interceptor. Any ideas?

EDIT: Or would I have to do this in a filter?

tallkid24
  • 1,697
  • 4
  • 16
  • 20
  • you should be able to modify request at preHandle() in HandlerInterceptorAdapter – kuhajeyan Oct 12 '16 at 18:50
  • 2
    @kuhajeyan I don't see a way that you can actually modify the request in the interceptor since it doesn't actually return the request object. Maybe I'm missing something? – tallkid24 Oct 12 '16 at 19:22

3 Answers3

3

HttpServletRequest type objects are read only, to do that you should:

-> create a class which extends HttpServletRequestWrapper (to add some behaviours, decorator pattern)

final public class MutableHttpServletRequest extends HttpServletRequestWrapper {

    private final Map<String, String> customHeaders;

    public MutableHttpServletRequest(HttpServletRequest request){
        super(request);
        this.customHeaders = new HashMap<String, String>();
    }

    public void putHeader(String name, String value){
        this.customHeaders.put(name, value);
    }

    public String getHeader(String name) {
        String headerValue = customHeaders.get(name);

        if (headerValue != null){
            return headerValue;
        }
        return ((HttpServletRequest) getRequest()).getHeader(name);
    }

    public Enumeration<String> getHeaderNames() {
        Set<String> set = new HashSet<String>(customHeaders.keySet());

        @SuppressWarnings("unchecked")
        Enumeration<String> e = ((HttpServletRequest) getRequest()).getHeaderNames();
        while (e.hasMoreElements()) {
            String n = e.nextElement();
            set.add(n);
        }
        return Collections.enumeration(set);
    }
}

-> create your filter class

public class CustomGatewayFilter implements Filter {

    @Override
    public void doFilter(ServletRequest request, ServletResponse response,
                         FilterChain chain) throws IOException, ServletException {
        HttpServletRequest req = (HttpServletRequest) request;
        MutableHttpServletRequest mutableRequest = new MutableHttpServletRequest(req);
        mutableRequest.putHeader("referer", "custom value");
        chain.doFilter(mutableRequest, response);
    }
}

-> and in your config class add

 .and().addFilterAfter(new CustomGatewayFilter(), ConcurrentSessionFilter.class)
Walterwhites
  • 1,287
  • 13
  • 9
  • Original solution here: http://wilddiary.com/adding-custom-headers-java-httpservletrequest/ – pringi Jul 13 '21 at 17:22
0

The example from http://wilddiary.com/adding-custom-headers-java-httpservletrequest/ doesn't seem to work for me with Tomcat 9. I know it gets into the filter because I send the values I want to stdout and I know if I comment chain.doFilter line, then the page is blank because I'm not writing out any headers.

  • This does not provide an answer to the question. Once you have sufficient [reputation](https://stackoverflow.com/help/whats-reputation) you will be able to [comment on any post](https://stackoverflow.com/help/privileges/comment); instead, [provide answers that don't require clarification from the asker](https://meta.stackexchange.com/questions/214173/why-do-i-need-50-reputation-to-comment-what-can-i-do-instead). - [From Review](/review/late-answers/34684604) – Bö macht Blau Jul 17 '23 at 19:07
-4
public class YourInterceptor extends HandlerInterceptorAdapter {    

    @Override
    public boolean preHandle(HttpServletRequest request,
            HttpServletResponse response, Object handler) throws Exception {
        SomeModel model = new SomeModel();
        request.setAttribute("someValue", model );
        request.addHeader("xxx","asecret");

        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request,
            HttpServletResponse response, Object handler,
            ModelAndView modelAndView) throws Exception {
        //...
         response.addHeader("dummy-header, "dummy-value");
    }

    @Override
    public void afterCompletion(HttpServletRequest request,
            HttpServletResponse response, Object handler, Exception ex)
            throws Exception {
        SomeModel model = (Long) request.getAttribute("someValue");

    }

}
kuhajeyan
  • 10,727
  • 10
  • 46
  • 71
  • 5
    `HttpServletRequest` doesn't have a Method called `addHeader`. – Sal Oct 25 '17 at 10:04
  • Also, updating the `response` in `postHandle` will do nothing because it has already been committed at that point. – Igor Mar 20 '18 at 19:07