You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Node.js中Keycloak.protect()接口CORS阻塞问题求助

Keycloak保护路由时CORS拦截问题

使用keycloak.protect()保护/secured路由时,前端访问该路由被CORS策略拦截。已通过app.use(cors())配置允许所有跨域请求,且前端能正常获取ID Token。

相关代码

index.ts

import bodyParser from 'body-parser';
import cors from 'cors';
import express from 'express';
import KeycloakConnect from 'keycloak-connect';

const session = require('express-session');
const Keycloak = KeycloakConnect;

const app = express();
app.use(cors())
app.options('*', cors());

app.use(bodyParser.json());

const memoryStore = new session.MemoryStore();

app.use(session({
  secret: 'mysecret',
  resave: false,
  saveUninitialized: true,
  store: memoryStore
}));

const keycloak = new Keycloak({store: memoryStore});

app.use(keycloak.middleware({
  logout: "/logout",
  admin: "/"
}));


app.use(cors());

app.get('/service/public', function (req, res) {
  console.log('Server started on port 3000');
});

app.get('/secured', keycloak.protect(), function (req, res) {
  console.log('Server started on port 3000');
});

app.get('/service/admin', keycloak.protect('realm:admin'), function (req, res) {
  res.json({message: 'admin'});
});


app.listen(3000, () => {
  console.log('Server started on port 3000');
});

keycloak.json

{
  "realm": "QRCoffee",
  "auth-server-url": "http://localhost:8080/auth",
  "ssl-required": "external",
  "resource": "QRCoffee",
  "public-client": true,
  "confidential-port": 0
}

CORS错误信息

Access to fetch at 'http://localhost:8080/auth/realms/QRCoffee/protocol/openid-connect/auth?client_id=QRCoffee&state=7321400d-3c51-4c53-8c9a-100101239845&redirect_uri=http%3A%2F%2Flocalhost%3A3000%2Fsecured%3Fauth_callback%3D1&scope=openid&response_type=code' (redirected from 'http://localhost:3000/secured') from origin 'http://localhost:5173' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.

已做排查操作

  • 已开启所有URL的跨域配置:正常
  • 前端可正常获取Keycloak令牌:正常
  • 尝试开启Keycloak端的跨域配置
  • 访问未受keycloak.protect()保护的路由:无问题
  • 前端已成功连接Keycloak

期望实现

已登录Keycloak时可正常访问/secured路由。

内容的提问来源于stack exchange,提问作者Julien Bertrand

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.29 00:45:35