Answer a question

How do you correctly configure NGINX as a proxy in front of Keycloak?

Asking & answering this as doc because I've had to do it repeatedly now and forget the details after a while.

This is specifically dealing with the case where Keycloak is behind a reverse proxy e.g. nginx and NGINX is terminating SSL and pushing to Keycloak. This is not the same issue as keycloak Invalid parameter: redirect_uri although it produces the same error message.

Answers

The key to this is in the docs at https://www.keycloak.org/docs/latest/server_installation/index.html#identifying-client-ip-addresses

The proxy-address-forwarding must be set as well as the various X-... headers.

If you're using the Docker image from https://hub.docker.com/r/jboss/keycloak/ then set the env. arg -e PROXY_ADDRESS_FORWARDING=true.

server {
  server_name api.domain.com;

  location /auth {
    proxy_set_header        Host $host;
    proxy_set_header        X-Real-IP $remote_addr;
    proxy_set_header        X-Forwarded-For $proxy_add_x_forwarded_for;
    proxy_set_header        X-Forwarded-Proto $scheme;

    proxy_pass          http://localhost:8080;
    proxy_read_timeout  90;

 }

  location / {
    proxy_set_header        Host $host;
    proxy_set_header        X-Real-IP $remote_addr;
    proxy_set_header        X-Forwarded-For $proxy_add_x_forwarded_for;
    proxy_set_header        X-Forwarded-Proto $scheme;

    proxy_pass          http://localhost:8081;
    proxy_read_timeout  90;
  }



    listen 443 ssl; # managed by Certbot
    ssl_certificate /etc/letsencrypt/live/api.domain.com/fullchain.pem; # managed by Certbot
    ssl_certificate_key /etc/letsencrypt/live/api.domain.com/privkey.pem; # managed by Certbot
    include /etc/letsencrypt/options-ssl-nginx.conf; # managed by Certbot
    ssl_dhparam /etc/letsencrypt/ssl-dhparams.pem; # managed by Certbot

}
server {
    if ($host = api.domain.com) {
        return 301 https://$host$request_uri;
    } # managed by Certbot


  server_name api.domain.com;
    listen 80;
    return 404; # managed by Certbot
}

If you're using another proxy the important parts of this is the headers that are being set:

proxy_set_header        Host $host;
proxy_set_header        X-Real-IP $remote_addr;
proxy_set_header        X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header        X-Forwarded-Proto $scheme;

Apache, ISTIO and others have their own means of setting these.

Logo

开发云社区提供前沿行业资讯和优质的学习知识,同时提供优质稳定、价格优惠的云主机、数据库、网络、云储存等云服务产品

更多推荐