Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to add HttpServletRequest headers in HandlerInterceptorAdapter?

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?

like image 823
tallkid24 Avatar asked Oct 12 '16 18:10

tallkid24


Video Answer


1 Answers

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)
like image 178
Walterwhites Avatar answered Oct 16 '22 23:10

Walterwhites