Keycloak behind apache reverse proxy

后端 未结 5 1185
春和景丽
春和景丽 2020-12-24 09:38

I have surfed through google without finding any concrete answers or examples, so again trying my luck here (often get lucky).

5条回答
  •  一整个雨季
    2020-12-24 10:30

    I've had a similar problem in a docker swarm environment. My Keycloak and my spring boot container were both behind the same reverse proxy.

    For Tomcat: The matter is to configure the http(s) connector correctly. Let's say the host name and port of our reverse proxy are http://${EXTERNAL_HOSTNAME}:${EXTERNAL_PORT}.

    Then the http(s) connector in tomcat.xml should have those two additional attributes:

    
    

    This will make all calls to servletRequest.getServerName() and servletRequest.getServerPort() respond with the values of our reverse proxy. The keycloak adapter certainly uses these functions to determine the redirect url.

    For Spring Boot: Drop this class in your classpath:

    @Component
    public class TomcatReverseProxyCustomizer implements WebServerFactoryCustomizer, TomcatConnectorCustomizer {
    
        @Value("${server.tomcat.proxy-name}")
        private String proxyName;
        @Value("${server.tomcat.proxy-port}")
        private int proxyPort;
    
        @Override
        public void customize(final TomcatServletWebServerFactory factory) {
            factory.addConnectorCustomizers(this);
        }
    
        @Override
        public void customize(final Connector connector) {
            connector.setProxyName(this.proxyName);
            connector.setProxyPort(this.proxyPort);
        }
    
    }
    

    and then setting this in application.properties:

    server.tomcat.proxy-name=${EXTERNAL_HOSTNAME}
    server.tomcat.proxy-port=${EXTERNAL_PORT}
    

    Additional Configuration of the keycloak adapter (Examples are for Spring Boot):

    My keycloak is also behind the same reverse proxy. So I also had to set the auth server url of the keycloak adapter to the hostname of the reverse proxy. Then I abused the proxy setting of the keycloak adapter to make it use the services on the internal leg:

    keycloak.auth-server-url=http://${EXTERNAL_HOSTNAME}:${EXTERNAL_PORT}/auth
    keycloak.proxy-url=http://${INTERNAL_KEYCLOAK_HOSTNAME}:${INTERNAL_KEYCLOAK_PORT}/auth
    

    Also these settings might make some sense:

    server.servlet.session.cookie.domain=${EXTERNAL_HOSTNAME}
    server.use-forward-headers=true
    server.tomcat.remote-ip-header=x-forwarded-for
    server.tomcat.protocol-header=x-forwarded-proto 
    

    server.tomcat.protocol-header is important for those who terminate SSL on their reverse proxy.

提交回复
热议问题