Adding Headers to Zuul when re-directing

Bocky picture Bocky · Apr 26, 2018 · Viewed 17.1k times · Source

I am trying to use Zuul to redirect calls to a downstream system somewhere else. In the re-direct, I need to add in a Header with necessary data for the api receiving the redirection to process. I can't seem to get the downstream system to detect this data. Attached is my code. I am using Zuul from Edgware.SR3, Spring Boot 1.5.12

Zuul Filter

@Component
public class RouteFilter extends ZuulFilter{

@Override
public Object run() {
//Testing to add header
    context.getRequest().getParameterMap().put("api", new String[]{"api"});
    context.getResponse().setHeader("api", api);
    context.addZuulResponseHeader("api", "api");
    context.addZuulRequestHeader("api", "api");
    context.setSendZuulResponse(false);
    context.put(FORWARD_TO_KEY, redirect_urls.get(key));
    context.setResponseStatusCode(HttpStatus.SC_TEMPORARY_REDIRECT);
    context.getResponse().sendRedirect(redirect_urls.get(key));
    return null;
}
}

Redirected Service Code

@RequestMapping(value = "/forward")
public ResponseEntity<String> forwardToMe(@RequestHeader(required = true, name = "api")String api){
    return new ResponseEntity<String>("Hi",HttpStatus.OK);
}

Error Received in Postman

{ "timestamp": 1524737817729, "status": 400, "error": "Bad Request", "exception": "org.springframework.web.bind.ServletRequestBindingException", "message": "Missing request header 'api' for method parameter of type String", "path": "/forward" }

Answer

redoff picture redoff · Apr 27, 2018

I guess you use a Route Filter, maybe you can try with a Pre Filter.

Adding a custom header can be done with something like this : context.addZuulRequestHeader("Authorization", "Basic " + credentials);.

For the redirection part, you can check this thread