I have an application which successfully authenticates users and their respective sessions using express-session, passport-local, and connect-ensure-login.

When replacing passport's Local Login strategy with a passport-azure-ad Bearer OAuth Strategy, I find that routes which previously found users sessions with the middleware:

require('connect-ensure-login').ensureLoggedIn()

No longer function - The call to req.isAuthenticated() will return false.

I can see that the session cookie connect.sid is still being set after Bearer OAuth Strategy success.

I suppose my question is: is there something which passport-local is doing to enable sessions which passport-azure-ad is not?

Server setup:

const bearerToken = require('express-bearer-token');
const app = express();
app.set('trust proxy', 1)
const dataRouter =  express.Router();
dataRouter.use(bearerToken());
dataRouter.use(require('cookie-parser')());
dataRouter.use(bodyParser.urlencoded({ extended: false }));
dataRouter.use(bodyParser.json());
dataRouter.use(session({secret: 'fake secret', resave: false, saveUninitialized: false}));
dataRouter.use(passport.initialize());
dataRouter.use(passport.session());

Route setup:

router.post('/sign-in', passport.authenticate('oauth-bearer'), (req, res) => {
    res.json({ user: req.user.username } });
});
router.get('/check-session', require('connect-ensure-login').ensureLoggedIn(), (req, res) => {
    res.json({ user: req.user.username } });
});

Passport setup:

const LocalStrategy = require('passport-local').Strategy;
const BearerStrategy = require('passport-azure-ad').BearerStrategy;

passport.use(new BearerStrategy(config.credentials, (req, token, done) => {
    let currentUser = null;
    let userToken = authenticatedUserTokens.find((user) => {
        currentUser = user;
        user.sub === token.sub;
    });

    if(!userToken) {
        console.log('No previous user token found');
        authenticatedUserTokens.push(token);
        currentUser = token.unique_name;
    }
    return done(null, currentUser, token);
});

passport.use('local-login', new LocalStrategy({
    usernameField: 'username',
    passwordField: 'password',
    passReqToCallback: true
},
function(req, username, password, done) {
    col.findOne({ 'local.username': username}, function(err, user) {
        if (err) {
            return done(err);
        }
        if (!user) {
            return done(null, false);
        }
        if (!validPassword(password, user.local.password)) {
            return done(null, false)
        }
        return done(null, user);
    });
}));

passport.serializeUser(function(req, user, done) {
    done(null, user._id.toString()); 
});

passport.deserializeUser(function(id, done) {
    const _id = new ObjectId(id);
    col.findOne({ _id: _id}, function(err, user) {
        if (err) {
            return done(err);
        }
        if (!user) {
            return done(null, false);
        }
        done(null, user);
    });
});

0 Answers