Oidc middleware issues: ensureAuthenticated() doesn't work and userinfo isn't set

Hi

i’m using node and trying to get the oidc middleware working but it is rather temperamental

the login works but the following don’t:

oidc.ensureAuthenticated()

and there is nothing in req.userinfo after login

What am i missing? incorrect config or something else?

Does anyone have a more comprehensive working example of the oidc node middleware being used?

Thanks

Can you share your code or your configuration?

Hi Tom … my code is below

In a fresh browser session, the initial okta login window appears and a redirect works but nothing beyond that (note URLs modified a bit as it wouldn’t let me post)

const express = require('express');
const session = require('express-session');
const { ExpressOIDC } = require('@okta/oidc-middleware');

// session support is required to use ExpressOIDC

const app = express();

app.use(session({
  secret: 'my secret',
  resave: true,
  saveUninitialized: false

}));

const oidc = new ExpressOIDC({
  issuer: '<URL> .../oauth2/default',
  client_id: '----------------------',
  client_secret: '-----------------------------------------',
  redirect_uri: '<URL> ... /authorization-code/callback',
  scope: 'openid profile',
  routes: {
    callback: {
      defaultRedirect: '/home'
    }
  }
});

app.get('/', (req, res) => {
  console.log("/ handler");
  console.log("Authenticated: ", req.isAuthenticated());
  console.log(req.session);
  if (req.userinfo) {     // or req.isAuthenticated()
    res.send(`Hi ${req.userinfo.name}! you are logged in`);
  } else {
    res.send('Hi! not logged in ...');
  }

});

app.get('/home', (req, res) => {
  console.log("/home handler");
  console.log(req.session);
  console.log(req.userinfo);
  res.send('you got to /home');
});

//app.get('/protected', oidc.ensureAuthenticated(), (req, res) => {
app.get('/protected', (req, res) => {
  console.log("/protected handler");
  //console.log(oidc.access_token);
  console.log(req.userinfo);
  oidc.ensureAuthenticated();
  res.send('Protected stuff');
});


app.get('/logout', (req, res) => {
  console.log("/logout handler");
  req.logout();
  res.redirect('/');
});

// ExpressOIDC will attach handlers for the /login and /authorization-code/callback routes

app.use(oidc.router);

oidc.on('ready', () => {
  app.listen(8081, () => console.log(`Started!`));
});

oidc.on('error', err => {
  console.log('Unable to configure ExpressOIDC', err);
});

Hi @JMK, thank you for providing your code. You should be able to solve your problem by moving app.use(oidc.router); above your other route definitions. The OIDC router sets up all the middleware that is needed to later use oidc.ensureAuthenticated(). We will update our documentation to make this clearer.

I also see that you have a call to oidc.ensureAuthenticated() inside of your protected route handler, that should be removed.

1 Like

Robert … thanks, all fixed!