PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Saturday, June 25, 2022

[FIXED] how to force hostname when behind a chain of 2 revese proxy

 June 25, 2022     java, reverse-proxy, spring, spring-boot     No comments   

Issue

An spring boot application is hosted behind 2 reverse proxy (chained).

reverse-proxy 1 --> reverse-proxy 2 --> spring boot app

And the host and forward headers are not chain correctly. there is a way to force the host to a fixed value? like the hostname of the "reverse proxy 1"?


Solution

i have fixed my issue by changing the serverName in incoming request.

i have add a valve to tomcat:

public class HostForceValve extends ValveBase {

private final String proxyName;

public HostForceValve(String proxyName) {
    this.proxyName = proxyName;
}

@Override public void invoke(Request request, Response response) throws IOException, ServletException {
    org.apache.coyote.Request coyoteRequest = request.getCoyoteRequest();
    MimeHeaders mimeHeaders = coyoteRequest.getMimeHeaders();
    mimeHeaders.removeHeader("host");
    final MessageBytes host = mimeHeaders.addValue("host");
    host.setString(proxyName);
    request.setRemoteHost(proxyName);
    request.getCoyoteRequest().serverName().setString(proxyName);
    try {
        Valve next = getNext();
        if (null == next) {
            return;
        }
        next.invoke(request, response);
    } finally {
        request.setRemoteHost(proxyName);
    }

}
}

And add this value to the tomcat embedded server:

@Component
public class MyTomcatCustomizer implements WebServerFactoryCustomizer<TomcatServletWebServerFactory> {

@Value("${proxyName:}")
private String proxyName;

@Override
public void customize(TomcatServletWebServerFactory factory) {
    final Collection<Valve> currents = factory.getEngineValves();
    final ArrayList<Valve> addValves = new ArrayList<>(currents);
    if (StringUtils.hasLength(proxyName)) {
        addValves.add(0, new HostForceValve(proxyName));
    }
    factory.setEngineValves(addValves);
}
}


Answered By - RJO
Answer Checked By - Willingham (PHPFixing Volunteer)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing