Search code examples
node.jsauthenticationactive-directorypassport.jsunauthorized

PassportJS authenticates user but returns 401 Unauthorized on subsequent requests


I'm writing one of my first applications in NodeJS so please bear with me. I've managed to successfully authenticate a user to our Active directory and I can see the connect.sid cookie being set and used on the subsequent requests.

Upon debugging the application by dumping the req object I can also see that the user variable has been set successfully. From the documentation I've read that seems to be a criteria for a successful session match?

However, the request is still getting a 401 Unauthorized.

To summarize:

  1. The user is successfully authenticated after posting credentials /login.
  2. Upon successful authentication the user is redirected to "/".
  3. The "/" path replies with 401 Unauthorized.

Any ideas much appreciated. Code below.

const express = require('express');
var bodyParser = require('body-parser');
var session = require('express-session');
var passport = require('passport')
var ActiveDirectoryStrategy = require('passport-activedirectory')

// Setup the authentication strategy
passport.use(new ActiveDirectoryStrategy({
    integrated: false,
    ldap: {
        url: 'ldap://myad.company.com',
        baseDN: 'DC=domain,DC=company,DC=com',
        username: 'user',
        password: 'password'
    }
}, function (profile, ad, done) {
    ad.isUserMemberOf(profile._json.dn, 'Group', function (err, isMember) {
        if (err) return done(err)
        return done(null, profile)
    })
}));

passport.serializeUser(function(user, done) {
    done(null, JSON.stringify(user));
  });

passport.deserializeUser(function(user, done) {
    done(null, JSON.parse(user));
});

const app = express();

app.use(bodyParser.urlencoded({extended: true}));
app.use(session(
    { secret: "password" }
));
app.use(passport.initialize());
app.use(passport.session());

// For debugging purposes
app.use(function (req, res, next) {
    console.log(req)
    next()
})

// The login page posts a form containing user and password
app.get("/login", (req, res) => {
    res.sendFile(__dirname + '/public/index.html');
})

// Handler for the login page. Receives user and password and redirects the user to /
app.post('/login', 
    passport.authenticate('ActiveDirectory', {
            failWithError: true,
            successRedirect: "/",
            failureRedirect: "/login"
        }
    ), function(req, res) {
        res.json(req.user)
    }, function (err) {
        res.status(401).send('Not Authenticated')
    }
)

// This is where the issue happens. The page returns "Unauthorized".
// Using console.log(req) shows that the user property has been set to the req object.
// However, for some reason it still fails.
app.get('/',
    passport.authenticate('ActiveDirectory', {
            failWithError: true,
        }
    ), function(req, res) {
        res.send("test")
}, function (err) {
    res.status(401).send('Not Authenticated')
})

Solution

  • Found what I did wrong!

    The .authenticate method is only used to validate credentials, not to validate a session.

    So this:

    app.get('/',
        passport.authenticate('ActiveDirectory', {
                failWithError: true,
            }
        ), function(req, res) {
            res.send("test")
    }, function (err) {
        res.status(401).send('Not Authenticated')
    })
    

    Should become:

    app.get('/', function(req, res, next) {
        // This is verifying that the user part has been populated,
        // which means that the user has been authenticated.
        if (req.user) {
            res.send('Returning with some text');
        } else {
            // If the user property does no exist, redirect to /login
            res.redirect('/login');
        }
      });
    

    Another thing that I changed was the serialize/deserialize functions:

    passport.serializeUser(function(user, done) {
        done(null, user);
      });
    
    passport.deserializeUser(function(user, done) {
        done(null, user);
    });
    

    This removes redundant serializing/deserializing.

    These articles really helped me understand the flow:

    Hope it helps someone else!

    /Patrik