How to make Spring Security application to run behind a proxy?

本小妞迷上赌 提交于 2019-11-30 19:45:10

Spring Security uses the following logic when sending a redirect:

public void sendRedirect(HttpServletRequest request, HttpServletResponse response, String url) throws IOException {
    String redirectUrl = calculateRedirectUrl(request.getContextPath(), url);
    redirectUrl = response.encodeRedirectURL(redirectUrl);

    if (logger.isDebugEnabled()) {
        logger.debug("Redirecting to '" + redirectUrl + "'");
    }

    response.sendRedirect(redirectUrl);
}

The sendRedirect method is required to behave in the following way:

This method can accept relative URLs; the servlet container must convert the relative URL to an absolute URL before sending the response to the client.

That means you will by deafult always get an absolute URL, no matter what's the configuration or context setting.

You have multiple options:

  • configure your container or application server to be aware of the public URL (for example by using AJP instead of HTTP reverse proxy, or passing HTTP headers with the public URL which is supported by some application servers), e.g. documentation for Tomcat
  • configure your HTTP reverse proxy to perform correct rewriting, e.g. see ProxyPassReverse in Apache mod_proxy documentation
  • implement a custom org.springframework.security.web.RedirectStrategy where you will manually set the Location response header and HTTP 302 status code, this should allow you to send context relative redirect as you want
Lost Carrier

Not entirely relative, but probably you might want to have a look into a 4th option using the org.springframework.web.servlet.view.UrlBasedViewResolver to rewrite the redirected URL with your external hostname as described in this answer: Override the default redirect URL in a SpringMVC application.

Moebius

That should be achievable on Apache with:

ProxyPreserveHost Off
ProxyPass / http://192.168.0.10:8090
ProxyPassReverse / http://192.168.0.10:8090

and adding one more proxy reverse on the proxing host with the port. E.g supposing your server name is proxy.example.com the fourth line would be:

ProxyPassReverse / http://proxy.exemple.com:8090

Look at this answer: Sending redirect in Tomcat web application behind a Apache 2 proxy (mod_proxy)

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!