我的代码粘贴在下面。在回调方法中,我设置了用户,但是当我重定向到'/'时,用户不再可用。我正在使用护照和客户会话。任何帮助将不胜感激。我最初使用的是req.session,并根据link
进行了更改谢谢。
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("/");
});
在我的app.js中,我有以下代码:
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());
答案 0 :(得分:0)
我发现this article非常有用,特别是这一点:
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();
}
});
答案 1 :(得分:0)
Passport希望将会话cookie命名为“ session”。只要您设置client-sessions
,就可以将express-session
替换为{cookieName: 'session'}
。确保删除express-session
,否则两者将冲突。
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());