简体   繁体   中英

How can I capture J2EE redirects?

I have a Spring Boot application running inside a Docker container. The container exposes port 80, though I have load balancer that accepts both HTTP and HTTPS traffic (and forwards both onto port 80 of the container).

The trouble I'm having is that although HTTPS works, the application running inside container seems to think that all the traffic is coming from HTTP, even though it does have access to the original request URL. What I mean by that is: if I access https://www.mycontainerapp.whatever the page will load. But if I go to any URL path that triggers a redirect, eg https://www.mycontainerapp.whatever/redirect-to-something-else , the application always redirects to http://www.mycontainerapp.whatever/redirect-target with plain HTTP, losing the HTTPS.

I confess that I don't necessarily know the right J2EE terminology for what kind of class I'd like to write. Maybe it's a Filter, or an Interceptor, or a Connector, or some other kind of Servlet class. All I plan on doing is writing a class that checks if the original request started with "https", and makes sure the final redirect URL also contains https. I'm just not sure what the right entry point is for that. How can I "capture" a redirect like this?

If you want to do correct redirect with elb terminated ssl, you need to query x-forwarded-proto header and checks if it is https . In this case, you then redirect with appopriate protocol

@WebFilter(urlPattern = "/")
public class RedirectDetectFilter implements Filter {
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) {
        // Detect and do redirect here
        HttpServletRequest servletRequest = (HttpServletRequest)request;
        HttpServletResponse servletResponse = (HttpServletResponse)response
        if(isRedirectNeeded(servletRequest, servletResponse) {
             // build absoulute url with protocol:
             String protocol = servletRequest.getheader(X-FORWARDED-PROTO);
             String absUrl = format("%s://%s/%s", protocol, host, redirectUrl);
             servletResponse.sendRedirect(absUrl);
        } else {
            chain.doFilter(request, response);
        }
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM