jaredhanson / passport

Simple, unobtrusive authentication for Node.js.
https://www.passportjs.org?utm_source=github&utm_medium=referral&utm_campaign=passport&utm_content=about
MIT License
22.92k stars 1.24k forks source link

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

Open anthonyorona opened 3 years ago

anthonyorona commented 3 years ago

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;
YasharF commented 1 year ago

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.