Trung Tran
Trung Tran

Reputation: 13721

PassportJS serializeUser and deserializeUser not working

I am using PassportJS to authenticate my node.js application. I'm using the WSFED/ADFS strategy. However, my passport.serializeUser() and passport.deserializeUser() functions are not working. They are not even called. The typical solution I have found is to add app.use(passport.initialize()) and app.use(passport.session()) AFTER app.use(session()), which I did so I'm not sure why serializeUser() and deserializeUser() are not being called. Here's my code:

    var express = require('express'),
        app = express(),
        bodyParser = require('body-parser'),
        cookieParser = require('cookie-parser'),
        session = require('express-session'),
        passport = require('passport'),
        wsfedsaml2 = require('passport-wsfed-saml2').Strategy;

    //Middlewares
    passport.use('wsfed-saml2', new wsfedsaml2({
        realm: 'https://localhost:3001',
        identityProviderUrl: 'https://some_company.org/adfs/ls/',
        thumbprint: '9.....4'
    },
    function(profile, done) {
        console.log(profile);
        return done(null, new User(profile));
    }));

    app.use(cookieParser());

    app.use(bodyParser.urlencoded({
        extended: true
    }));

    app.use(session({
      secret: 'keyboard cat',
      resave: false,
      saveUninitialized: true,
      cookie: { secure: true }
    }));

    app.use(passport.initialize());
    app.use(passport.session());

    passport.serializeUser(function(user, done) {
        console.log('In Serializer'); //does not print
        done(null, user);
    });

    passport.deserializeUser(function(user, done) {
        console.log('In DeSerializer'); //does not print
        done(null, user);
    });

Can someone help?

Thanks in advance!

Upvotes: 0

Views: 1233

Answers (3)

John Nico Novero
John Nico Novero

Reputation: 665

oh god i figured it out on my app. its just the arrangement.

my index.js

const express = require('express');
const mongoose = require('mongoose');
const cookieSession = require('cookie-session');
const passport = require('passport');
const keys = require('./config/keys');
require('./models/User')
require('./services/passport')

const auth = require('./routes/auth')
const profile = require('./routes/profile')

const app = express()

app.use(
    cookieSession({
        maxAge: 30 * 24 * 60 * 60 * 1000,
        keys: [keys.cookieKey],
    }),
);

//db
mongoose.connect(keys.mongooseURI, () => {
    console.log('Connected to mongodb')
})

app.use(passport.initialize())
app.use(passport.session())

app.use('/auth', auth)
app.use('/api', profile)

//server
const PORT = process.env.PORT || 5000
app.listen(PORT, () => {
    console.log('Server is running on PORT', PORT)
})

my passport .js

const passport = require('passport')
const GoogleStrategy = require('passport-google-oauth20').Strategy
const keys = require('../config/keys')
const mongoose = require('mongoose')
const User = mongoose.model('users')

passport.serializeUser((user, done) => {
    console.log('serialize', user)
    done(null, user.id)
});

passport.deserializeUser((id, done) => {
    console.log('deserialize', id)
    User.findById(id)
        .then(user => {
            console.log('user', user)
            done(null, user)
        })
});

passport.use(new GoogleStrategy(
    {
        clientID: keys.googleClientID,
        clientSecret: keys.googleClientSecret,
        callbackURL: '/auth/google/callback'
    },
    async (accessToken, refreshToken, profile, done) => {
        User.findOne({ googleID: profile.id })
            .then(existingUser => {
                existingUser ? done(null, existingUser) : new User({ googleID: profile.id }).save().then(user => { done(null, user) })
            })
    }
))

my package.json if u need

{
  "name": "react-nodejs",
  "version": "1.0.0",
  "main": "index.js",
  "license": "MIT",
  "dependencies": {   
    "cookie-session": "@latest",
    "express": "^4.17.3",   
    "mongoose": "^6.2.3",
    "nodemon": "^2.0.15",
    "passport": "@latest",
    "passport-google-oauth20": "^2.0.0"
  },
  "engines": {
    "node": "16.13.2",
    "npm": "8.1.2",
    "yarn": "1.22.17"
  },
  "scripts": {
    "dev": "nodemon index.js",
    "start": "node index.js"
  }
}

Upvotes: 0

Viktoria Postnova
Viktoria Postnova

Reputation: 11

Solved the same problem by removing cookie: { secure: true } HTTPS is necessary for secure cookies. If secure is set, and you access your site over HTTP, the cookie will not be set

app.use(session({
      secret: 'keyboard cat',
      resave: false,
      saveUninitialized: true,
    }));

Upvotes: 1

dsan
dsan

Reputation: 1578

Edited: I think you configured the passport strategy incorrectly. Looking at the docs, its looking like it should be:

passport.use(new wsfedsaml2({
    realm: 'https://localhost:3001',
    identityProviderUrl: 'https://some_company.org/adfs/ls/',
    thumbprint: '9.....4'
},
function(profile, done) {
    console.log(profile);
    return done(null, new User(profile));
}));

Upvotes: 0

Related Questions