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?
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With