首页 > 解决方案 > keycloak-js 初始化失败,因为祖先违反了内容安全策略指令:“frame-ancestors 'self'

问题描述

我有一个 NGINX (1.14.1),它将 /auth 请求转发到在云中运行的 Keycloak (14.0.0)。

这是 /etc/nginx/conf.d/my.domain.biz.conf 中的 NGINX 配置

server {
  listen 80;
  server_name my.domain.biz;
  return 301 https://$host$request_uri;
}

server {
  listen 443 ssl;
  server_name my.domain.biz;
  ssl_certificate /etc/letsencrypt/live/domain.biz/fullchain.pem;
  ssl_certificate_key /etc/letsencrypt/live/domain.biz/privkey.pem;
  location /auth {
    proxy_pass http://127.0.0.1:8080/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_set_header X-Scheme $scheme;
    add_header X-Frame-Options "ALLOW-FROM https://my.domain.biz/";
    add_header Content-Security-Policy "frame-src https://my.domain.biz/; frame-ancestors https://my.domain.biz/; object-src https://my.domain.biz/;";
  }
}

我可以在https://my.domain.biz/auth/的 Keycloak 管理控制台中创建领域和公共客户端。我可以从https://my.domain.biz/auth/realms/myrealm/.well-known/openid-configuration列出端点

另外,我在领域设置的安全防御中更新了以下两个值,

X-Frame-Options: ALLOW-FROM https://my.domain.biz
Content-Security-Policy: frame-src https://my.domain.biz/; frame-ancestors https://my.domain.biz/; object-src https://my.domain.biz/;

我在我的笔记本电脑上运行了一个带有keycloak-js 14.0.0的 React webapp,地址为 http://localhost:8044/,我想通过在云中运行的 Keycloak 对其进行身份验证。Keycloak 客户端使用以下内容进行初始化keycloak.json

{
  "realm": "myrealm",
  "auth-server-url": "https://my.domain.biz/auth/",
  "ssl-required": "external",
  "resource": "my-pkce",
  "public-client": true,
  "confidential-port": 0
}

和 React 代码片段,

  const kc = new Keycloak('/keycloak.json');
  ...
  await kc.init({
    onLoad: 'login-required',
    pkceMethod: 'S256',
    enableLogging: true
  });

在 http://localhost:8044/ 访问 webapp 时,它没有重定向到 Keycloak 的登录页面,Chrome 浏览器控制台中显示错误:

Refused to frame 'https://my.domain.biz/' because an ancestor violates the following Content Security Policy directive: "frame-ancestors 'self'".

NGINX 中只记录了一行/var/log/nginx/access.log

"GET /auth/realms/myrealm/protocol/openid-connect/3p-cookies/step1.html HTTP/1.1" 404 2032 "http://localhost:8044/" "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.164 Safari/537.36" "-"

你知道什么可能是错的吗?

标签: keycloakkeycloak-javascript

解决方案


推荐阅读