1
我正在嘗試使用passport.js,節點和續集創建應用程序。 但是,護照沒有像預期的那樣在會話中返回用戶。passport.js不會將用戶傳遞給會話
當我登錄req.session我得到這個:
Session {
cookie:
{ path: '/',
_expires: null,
originalMaxAge: null,
httpOnly: true,
secure: true } }
當我登錄req.session.passport我得到了一個未定義。
我該如何解決這個問題?
這是我的server.js:
const express = require('express');
const load = require('express-load');
const passport = require('passport');
const cookieParser = require('cookie-parser');
const bodyParser = require('body-parser');
const session = require('express-session');
// var app = express();
var app = module.exports = express();
// read cookies (needed for auth)
app.use(cookieParser());
// get information from html forms
app.use(bodyParser());
//set session
app.set('trust proxy', 1) // trust first proxy
app.use(session({
secret: 'asdasdsada',
resave: false,
saveUninitialized: true,
cookie: { secure: true }
}))
// required for passport
app.use(passport.initialize());
app.use(passport.session({
secret: 'adsdssa',
name: 'sadasd',
proxy: true,
resave: true,
saveUninitialized: true
}));
這是我passport.js:
var LocalStrategy = require('passport-local').Strategy;
var SlackStrategy = require('passport-slack').Strategy;
var User = require('../models/index').User;
var mysql = require('mysql');
var connection = mysql.createConnection({
host : process.env.MYSQL_HOST,
user : process.env.MYSQL_USER,
password : process.env.MYSQL_PASSWORD,
database : process.env.MYSQL_DB
});
module.exports = function(passport) {
passport.serializeUser(function(user, done) {
console.log('-----------serialize');
done(null, user.id);
});
passport.deserializeUser(function(id, done) {
console.log('----------deserialize');
Model.User.findOne({
where: {
'id': id
}
}).then(function (user) {
if (user == null) {
done(new Error('Wrong user id.'));
}
done(null, user);
})
});
passport.use('slack', new SlackStrategy({
clientID: process.env.SLACK_ID,
clientSecret: process.env.SLACK_SECRET,
callbackURL: process.env.SLACK_REDIRECT,
scope: "incoming-webhook users:read"
},
function(accessToken, refreshToken, profile, done) {
var values = {
where: { slack_id: profile.id },
defaults: {slack_id: profile.id, name: profile.displayName}
};
User.findOrCreate(values)
.spread(function(user, created) {
return done(null,user);
});
}
));
這些都是我使用的路線:
app.get('/auth/slack',
passport.authorize('slack'));
app.get('/auth/slack/callback',
passport.authorize('slack', { failureRedirect: '/login' }),
function(req, res) {
//Successful authentication, redirect home.
console.log(req.session);
console.log(req.session.passport);
res.redirect('/dashboard');
}
);
我這裏有同樣的問題的簡單的例子,僅僅因爲我使用了'passport.authorize()'而不是'passport.authenticate()'。 –