PassportJS authenticates user but returns 401 Unauthorized on subsequent requests

|▌冷眼眸甩不掉的悲伤 提交于 2021-01-27 19:39:40

问题


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')
})

回答1:


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:

  • http://toon.io/understanding-passportjs-authentication-flow/
  • https://www.airpair.com/express/posts/expressjs-and-passportjs-sessions-deep-dive

Hope it helps someone else!

/Patrik



来源:https://stackoverflow.com/questions/52641701/passportjs-authenticates-user-but-returns-401-unauthorized-on-subsequent-request

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!