我對這個問題感到瘋狂。我剛剛使用Google oAuth 2.0策略設置Passport js,並且在我本地的Express 4服務器上運行完美。Passport auth在本地工作,但不在遠程服務器上
但是,當我嘗試我的亞馬遜服務器調用req.isAuthenticated()返回false每次和req.user上運行它是不確定的。我無法弄清楚什麼是錯的。
passport.serializeUser(function(user, done) {
console.log("serializeUser " + user.id);
done(null, user.id);
});
passport.deserializeUser(function(id, done) {
console.log("deserializeUser: " + id);
User.find({_id: id}, function (error, user) {
if (error || !user) {
done(error, null);
} else {
done(null, user);
}
});
});
passport.use(new GoogleStrategy({
clientID: config.google.clientID,
clientSecret: config.google.clientSecret,
callbackURL: config.google.callbackURL
},
function(accessToken, refreshToken, profile, done) {
process.nextTick(function() {
if(profile._json.domain === 'xxx'){
var query = {googleId: profile.id};
var options = {upsert: true, new: true, setDefaultsOnInsert: true };
// Find the document
User.findOneAndUpdate(query, query , options, function (error, user) {
if (error) {
return done(error);
}
return done(null, user);
});
}else{
return done(new Error("Invalid host domain"));
}
});
}
));
router.get('/auth/google',
passport.authenticate('google', { scope: ['https://www.googleapis.com/auth/plus.login', 'https://www.googleapis.com/auth/userinfo.email'] }));
router.get('/auth/google/callback',
passport.authenticate('google', { failureRedirect: '/login' }), function(req, res) {
res.redirect('/');
});
router.get('/login', ensureAuthenticated, function(req, res){
console.log("User is Authenticated");
});
function ensureAuthenticated(req, res, next) {
console.log("USER " + req.user);
if (req.isAuthenticated()) {
console.log("Authorized");
return next();
} else {
console.log("Not authorized");
res.sendStatus(401);
}
}
而這是Express服務器的conf。
/ Express
var app = express();
app.use(cookieParser('xxx'));
app.use(bodyParser.json({limit: '100mb'}));
app.use(bodyParser.urlencoded({limit: '100mb', extended: true}));
// Used for production build
app.use(express.static(path.join(__dirname, 'public')));
app.use(session({
store: sessionStore, //var sessionStore = new MemoryStore();
secret: 'xxx',
resave: true,
saveUninitialized: true,
cookie: {
secure: false,
path: '/',
httpOnly: true,
maxAge: new Date(Date.now() + 3600000),
}
}));
// Compress responses
app.use(compression());
app.use(passport.initialize());
app.use(passport.session());
routes(app);
請幫幫忙!
是的重定向工作盡我所知。 – hxmn