使用GitHub策略时未定义Passport req.user

时间:2019-05-13 06:35:04

标签: node.js passport.js

我正在尝试使用护照设置Github身份验证。

app.js(我在其中设置了中间件)

var createError = require('http-errors');
var express = require('express');
var path = require('path');
var cookieParser = require('cookie-parser');
var logger = require('morgan');

const session = require('express-session');
const passport = require('passport');
const GitHubStrategy = require('passport-github').Strategy;


var indexRouter = require('./routes/index');

var app = express();
const helmet = require('helmet');

app.use(helmet());


const passportConfig = require('./config');

//================================PASSPORT CONFIG=======================    
app.use(session({
    secret: 'test1234',
    resave: false,
    saveUninitialized: true,
    cookie: { secure: true }
}));

app.use(passport.initialize());
app.use(passport.session());
passport.use(new GitHubStrategy(passportConfig,
    function (accessToken, refreshToken, profile, cb) {
        return cb(null, profile)
    }
));

passport.serializeUser(function(user, done) {
    done(null, user.id);
});

passport.deserializeUser(function(id, done) {
    done(null, user);
});

// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'ejs');

app.use(logger('dev'));
app.use(express.json());
app.use(express.urlencoded({extended: false}));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));

app.use('/', indexRouter);

// catch 404 and forward to error handler
app.use(function (req, res, next) {
    next(createError(404));
});

// error handler
app.use(function (err, req, res, next) {
    // set locals, only providing error in development
    res.locals.message = err.message;
    res.locals.error = req.app.get('env') === 'development' ? err : {};

    // render the error page
    res.status(err.status || 500);
    res.render('error');
});

module.exports = app;

如您所见,我设置了快速会话并使用passport.initialize()和passport.session()

但是当我尝试在任何一条路线中检索req.user对象时,它都返回未定义。有谁知道这可能是什么原因?

1 个答案:

答案 0 :(得分:0)

我认为这是app.use(passport.session());中间件的问题,请在执行任何操作之前手动保存会话。

app.get('slack/callback', function(req,res){
    passport.authorize('slack');
    //Manually save session before redirect.
    req.session.save(function(){
        res.redirect('/someURL');
    });
})