0

I have been trying to use keycloak authentication and have been stuck on this for a while. This is my code

app.get('/', function(req,res){
res.render('login1');
});

app.get('/login', keycloak.protect(), function (req, res) {

res.render('dashboard', {
    result: JSON.stringify(JSON.parse(req.session['keycloak-token']), null, 4)
});
});

So what is happening is, when i go to hostname/login, it redirects me to a login page of my company (we are validating the company employees with their credentials), we have a redirect uri which is http://hostname/login/* , so after keycloak.protect() executes, and user enters his credentials, it goes into infinite loop and the message on the browser is, redirected too many times.

While, ideally what should have happened is, after getting validated, it should come back to /login route, and render dashboard page we have. but it is not happening.

ash007
  • 311
  • 4
  • 24
  • I guess you're using the KC javascript adapter? Which KC version? – Aritz Apr 17 '18 at 08:17
  • "keycloak-connect": "^3.3.0-cr.1" for nodejs – ash007 Apr 17 '18 at 09:11
  • I don't know about node adapter, but the KC java adapter maps against the `/sso/login` and `/sso/logout` endpoints by default. Nodejs one might do the same against `/login` and `/logout`. Why don't you change the redirect uri in KC config to be other one, for example `http://hostname/home` or any other from your application? – Aritz Apr 17 '18 at 09:20
  • 1
    i got it workin, i changed the version of the keycloak-connect to a previous version. and it got working fine – ash007 Apr 17 '18 at 10:21
  • @ash007 how did you determine which version of keycloak-connect to use? – Shekhar Sahu Apr 26 '21 at 06:29

1 Answers1

0

you forget to install the keycloak middleware inside your application, add the lines given below in your code, it will resolve the issue:

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

complete code sample given below:

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

var memoryStore = new session.MemoryStore();


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

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

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

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

app.use('/route1', keycloak.protect(), function(req, res){
 console.log("AAAA")
 res.json("AAAA")
})

// Server Start
app.listen(3000, function(){
  console.log("Server Started") 
})
Irtiza
  • 173
  • 4
  • 16