TypeError:无法读取未定义的属性“keycloak-token”

Posted

技术标签:

【中文标题】TypeError:无法读取未定义的属性“keycloak-token”【英文标题】:TypeError: Cannot read property 'keycloak-token' of undefined 【发布时间】:2021-12-01 21:20:18 【问题描述】:

我知道这里已经有很多这样的问题,但由于我是一名初级开发人员,所以没有一个对我真正有帮助。

我目前正在尝试完全复制以下文章:https://medium.com/devops-dudes/secure-front-end-react-js-and-back-end-node-js-express-rest-api-with-keycloak-daf159f0a94e

其中有人尝试使用 React JS 保护前端和使用 Keylcoak 保护 Node.js 后端(Express Rest API)。

但不知何故,如果我尝试启动 node-microservices 应用程序,我的控制台会一直显示 “Initializing Keycloak”,如果我尝试在浏览器中访问端点,它会显示:

TypeError: Cannot read property 'keycloak-token' of undefined

我做错了什么?

节点微服务代码:

index.js

const express = require('express');
var router = express.Router();
var app = express();

const keycloak = require('./keycloak-config.js').initKeycloak();
app.use(keycloak.middleware());

router.get('/user', keycloak.protect('user'), function (req, res) 
    res.send("Hello User");
);

router.get('/admin', keycloak.protect('admin'), function (req, res) 
    res.send("Hello Admin");
);

router.get('/all', keycloak.protect(['user', 'admin']), function (req, res) 
    res.send("Hello All");
);

app.get('/', function (req, res) 
    res.send("Server is up!");
);

app.listen(8081);

keycloak-config.js

var session = require('express-session');
var Keycloak = require('keycloak-connect');
const chalk = require('chalk');

let keycloak;

var keycloakConfig = 
    "realm": "Demo-Realm",
    "bearer-only": true,
    "auth-server-url": "http://localhost:8080/auth/",
    "ssl-required": "external",
    "resource": "node-microservice",
    "verify-token-audience": true,
    "use-resource-role-mappings": true,
    "confidential-port": 0,
    "realmPublicKey": "MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEA1SrR985UGLhBlCReW1p9ypcKbQhjHXDqS3DK78ihqGxLiwNWWsG/ilwD54HbxMjcVIl6hLXZbpd85oAr6HCSjRm8D6HGP6AVfva7s6pQcXmNWIeFGhwOSM/k2rjXkVGpCu3Yhg+Fnx03zA/nSlybhyYJrt/EftbjhCVO58WnAhEY8ytBHZQws+I85BzstClm3dSXj9EiWea6pqB7vpYkMy/nGUBgfOFn30Hqa2Pp7Dxkgd7+G/xRN2JDbg09etgZzt9kXVs1X6LbwAWG60qeNF2ZMCHTZeiHi0FRM7d7irRrc68orrFiEg2Gp7u3urr2ss4JOwSWe9QK/l3eZ3XS6QIDAQAB"
  ;

  function initKeycloak() 
      if(keycloak) 
          console.log("Returning existing Keycloak instance!");
          return keycloak;
      
      else 
          console.log("Initializing Keycloak...");
          var memoryStore = new session.MemoryStore();
          keycloak = new Keycloak(
              store: memoryStore,
              secret: 'any_key',
              resave: false,
              saveUnitialized: true
          , keycloakConfig);
          return keycloak;
      
  

  module.exports = 
      initKeycloak
  ;

【问题讨论】:

这能回答你的问题吗? How to fix 'TypeError: Cannot read property 'keycloak-token' of undefined' error in javascript? 【参考方案1】:

编辑:

You need to do it like the solution the documentation proposes, as otherwise the middleware will not find the keycloak connection.

--

我简要浏览了您链接的中篇文章,似乎该文章使用了一种复杂的方法来保护您的快速路线。

看看Official documentation of the NodeJS adapter for Keycloak (keycloak-connect),它比文章中描述的配置和使用方式要简单得多。 initKeycloak() 所做的是不必要地模仿 the frontend keycloak.js 的行为,它确实提供了一个 initKeycloak 方法来在前端初始化 Keycloak 授权服务。对于 Node 应用程序,只需在 index.js 中初始化一次 keycloak 即可。

我的服务使用注入的 Kubernetes 机密运行,这就是为什么所有环境变量和我在 index.ts 顶部设置 keycloak 的原因:

示例

import express from 'express';
import pgSession from 'connect-pg-simple';
import Keycloak from 'keycloak-connect';

const app = express();

const pgSessionInit = pgSession(session);

const pgSessionStore = new pgSessionInit(
    pool: pool,
    tableName: 'session',
    schemaName: 'foo',
    createTableIfMissing: true,
);

app.use(session(
    secret: process.env.SESSION_SECRET,
    resave: false,
    saveUninitialized: false,
    store: pgSessionStore
))

const keycloak = new Keycloak(
    store: pgSessionStore
);

// RequestHandler and Route definitions after this point

附带说明:包含堆栈跟踪对我们有很大帮助,以便我们更好地了解您的问题并为您指明正确的方向。 Node 在其 Error 对象上有一个附加属性,称为“stack”。

try
    // some code producing an Error
catch(e: unknown)
    if(e instanceof Error)
         console.error(e, e.stack); // Retrieve Error Message and stack
    

【讨论】:

以上是关于TypeError:无法读取未定义的属性“keycloak-token”的主要内容,如果未能解决你的问题,请参考以下文章

TypeError:无法读取未定义的属性“findAll”(expressjs)

TypeError:无法读取未定义的属性(读取“问题”)

TypeError:无法读取未定义的属性“babel”

TypeError:无法读取未定义的属性(读取“匹配”):

TypeError:无法读取未定义的属性“存在”

TypeError:无法在 gitlab 中读取未定义的属性(读取“读取”)