Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to fix 'TypeError: Cannot read property 'keycloak-token' of undefined' error in javascript?

I'm trying to use keycloak in my node project but I'm always getting the following message : Cannot read property 'keycloak-token' of undefined.

Before that, I've launched keycloak, I created a new realm 'Test' and a new user 'id_a' which for I've set a new password. I can access to the account with keycloak but I can't with my code. Can you please help me ?

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

var memoryStore = new session.MemoryStore();

let kcConfig = {
  clientId: "id_a",
  bearerOnly: true,
  serverUrl: 'http://localhost:8080/auth',
  realm: 'Test'
};

let keycloak = new Keycloak({ store: memoryStore }, kcConfig);

var app = express();

app.use( keycloak.middleware() );

app.get( '/complain', keycloak.protect(), function(req, res) {
  res.send('hello world');
});

app.listen(3001, function(){
  console.log('Server started on port 3001...')
});

the output is : 'TypeError: Cannot read property 'keycloak-token' of undefined' and I expect hello world

like image 521
user11440762 Avatar asked May 24 '19 06:05

user11440762


2 Answers

I had the same issue, but now it's working. You need to instantiate a session before running the keycloak middleware. The missing piece of code is as follows:

// Create a session-store to be used by both the express-session
// middleware and the keycloak middleware.

var memoryStore = new session.MemoryStore();

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

// Provide the session store to the Keycloak so that sessions
// can be invalidated from the Keycloak console callback.
//
// Additional configuration is read from keycloak.json file
// installed from the Keycloak web console.

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

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

Checkout the keycloak quick start for nodeJS for full code reference: https://github.com/keycloak/keycloak-quickstarts/blob/latest/service-nodejs/app.js

like image 109
Caio Castro Avatar answered Sep 18 '22 12:09

Caio Castro


The client is not a user account with a password, it's a client in the Test realm you have made. Create a new client, set the Client ID to something like 'node-backend' and then configure kConfig clientId as 'node-backend'.

Clients are applications, like Node, or Angular.

like image 27
Martz Avatar answered Sep 19 '22 12:09

Martz