passport icon indicating copy to clipboard operation
passport copied to clipboard

The passport deserializeUser callback is called for GET requests, but not PUT requests..

Open anthonyorona opened this issue 3 years ago • 1 comments

I have set up sessions with Express using boilerplate like shown. PUT requests are not working because the req.user object is never populated. When logging to console I have observed the deserializeUser callback is never called. Is this a bug, or is configuration of this library just really complicated :b

import express from 'express';

import redis from 'redis';
import { v4 as uuidv4 } from 'uuid';
import passport from 'passport';
import session from 'express-session';

const app = express();
const redisStore = require('connect-redis')(session);

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

app.use((req, res, next) => {
  try {
    res.header('Access-Control-Allow-Origin', '0.0.0.0:3001');
    res.header('Access-Control-Allow-Credentials', 'true');
    res.header('Access-Control-Allow-Methods', 'GET, POST, PUT, DELETE');
    res.header('Access-Control-Allow-Headers', 'Origin, X-Requested-With, Content-Type, Accept, Authorization, Cache-Control, Pragma');

    // intercept OPTIONS method
    if (req.method === 'OPTIONS') {
      res.sendStatus(204);
    } else {
      next();
    }
  } catch (e) {
    res.status(500).json({
        message: 'Internal Server Error', error: e.toString()
    });
  }
})

const redisClient = redis.createClient({
  host: process.env.RHOST,
  port: process.env.RPORT,
});

redisClient.on('error', (err) => {
  logger.log({
    level: 'error',
    location: 'Redis Client',
    message: err.toString()
  });
});

app.use(session({
  genid: (req) => uuidv4(),
  store: new redisStore({
    host: process.env.RHOST,
    port: process.env.RPORT,
    client: redisClient
  }),
  name: '_appSession',
  secret: process.env.COOKIE,
  resave: false,
  cookie: {
    sameSite: 'lax',
    secure: false,
    expires: false
  },
  saveUninitialized: true
}));

passport.use(localStrategy);
passport.serializeUser(serializeUserCallback);
passport.deserializeUser(deSerializeUserCallback);
app.use(passport.initialize());
app.use(passport.session());
app.use('/', indexRouter);

module.exports = app;

anthonyorona avatar Aug 26 '21 00:08 anthonyorona

A couple of things:

  1. You may want to set up routes for get and put/post. Like https://github.com/sahat/hackathon-starter/blob/7bac14339a6fbf7bb4b460ae84ccc8f08314cf28/app.js#L159
  2. You may want to authenticate the user on the get, then have csrf protection to make sure the put is coming from the same user, which has already been authenticated.

YasharF avatar Jul 21 '23 21:07 YasharF