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
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
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With