client-sessions module with passportjs

眉间皱痕 提交于 2019-12-23 02:41:00

问题


My code is pasted below. In the callback method, I set the user, but when I redirect to '/' the user is no longer available. I'm using passport and client-sessions. Any help would be greatly appreciated. I was initially using req.session and changed it as per this link

Thank you.

app.get('/', function (req, res) {
if (req.session_state.user == null) {
passport.authenticate('azureoauth', { failureRedirect: './'})
}
else {
res.render('index', {user: req.session_state.user});
}
});

//This gets called by an external internet application

app.get('/auth/azureOAuth/callback', 
passport.authenticate('azureoauth', {}),
function (req, res) {
req.session_state.user = req.user;
res.redirect("/");
});

And in my app.js, I have the following code:

const clientSession = require("client-sessions");
app.use(clientSession({secret: 'blablabla', duration: 1000 * 60 * 60 * 24 * 365 * 10}));
app.use(passport.initialize()); // for user authentication/authorization
app.use(passport.session());

回答1:


I found this article pretty useful, particularly this particular bit:

app.use(function(req, res, next) {
  if (req.session && req.session.user) {
    User.findOne({ email: req.session.user.email }, function(err, user) {
      if (user) {
        req.user = user;
        delete req.user.password; // delete the password from the session
        req.session.user = user;  //refresh the session value
        res.locals.user = user;
      }
      // finishing processing the middleware and run the route
      next();
    });
  } else {
    next();
  }
});



回答2:


Passport expects the session cookie to be named "session". client-sessions can be used as a drop-in replacement for express-session so long as you set {cookieName: 'session'}. Make sure to remove express-session or the two will conflict.

const config = require('config');
const express = require('express');
const passport = require('passport');
const sessions = require('client-sessions');

const app = express();

// passport expects the cookie to be named "session"
app.use(sessions({
    secret: config.get('SESSION_SECRET'), // extremely secret
    cookieName: 'session', // automatically used by passport sessions
}));

// config passport
passport.use(SomeStrategy);
passport.serializeUser((user, done) => done(null, JSON.stringify(user)));
passport.deserializeUser((userStr, done) => done(null, JSON.parse(userStr)));
app.use(passport.initialize());
app.use(passport.session());


来源:https://stackoverflow.com/questions/32250185/client-sessions-module-with-passportjs

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