首页 > 解决方案 > Nginx 后面的 Keycloak 管理控制台配置为使用 HTTPS

问题描述

我正在尝试设置 Keycloak,但是教程希望我访问http://localhost:8080,但我将其设置在远程主机上并且需要从外部访问管理控制台。我试图通过 Nginx 公开它。Keycloak 管理控制台似乎可以无缝地使用新域名和端口,但它仍然尝试使用“http”网址而不是“https”网址(我已将 Nginx 配置为将 HTTP 重定向到 HTTPS,我想保留出于安全原因,这样做)。我发现问题在于它在内部设置了一个变量:

var authServerUrl = 'http://example.com/auth';

虽然正确的网址是https://example.com/auth.

结果,当我https://example.com/auth/admin/master/console/在浏览器中打开时,出现错误:

Refused to frame 'http://example.com/' because it violates the following Content Security Policy directive: "frame-src 'self'".

如何解决?我使用的 Nginx 配置是:

server {
    server_name    example.com;

    listen         80;
    listen         [::]:80;

    location / {
      return         301 https://$server_name$request_uri;
    }
}

ssl_session_cache shared:ssl_session_cache:10m;

server {
    server_name example.com;

    listen 443 ssl http2;
    listen [::]:443 ssl http2;

    # ... <SSL and Gzip config goes here> ...

    location / {
        proxy_http_version 1.1;
        proxy_set_header Upgrade $http_upgrade;
        proxy_set_header Connection "upgrade";
        proxy_set_header Host $http_host;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;

        proxy_pass http://127.0.0.1:8080;

        client_max_body_size 16m;
    }
}

标签: nginxkeycloak

解决方案


您正在 nginx 中进行 SSL 卸载,但您需要将使用 https 模式的信息也转发到 Keycloak(X-Forwarded-Proto标头)。尝试这个:

server {
    server_name    example.com;

    listen         80;
    listen         [::]:80;

    location / {
      return         301 https://$server_name$request_uri;
    }
}

ssl_session_cache shared:ssl_session_cache:10m;

server {
    server_name example.com;

    listen 443 ssl http2;
    listen [::]:443 ssl http2;

    # ... <SSL and Gzip config goes here> ...

    location / {
        proxy_http_version 1.1;
        proxy_set_header Upgrade $http_upgrade;
        proxy_set_header Connection "upgrade";
        proxy_set_header Host $http_host;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_set_header X-Real-IP $remote_addr;
        proxy_set_header X-Forwarded-Host $host;
        proxy_set_header X-Forwarded-Server $host;
        proxy_set_header X-Forwarded-Port $server_port;
        proxy_set_header X-Forwarded-Proto $scheme;        
        proxy_pass http://127.0.0.1:8080;

        client_max_body_size 16m;
    }
}

推荐阅读