如何与护照举行会议?

时间:2018-03-19 10:38:28

标签: node.js redux passport.js passport-local

所以,我希望我的用户会话能够在登录/注册时保持不变,但事实并非如此。

官方文档说要添加以下内容:

  app.use(express.session({ secret: 'keyboard cat' }));
  app.use(passport.initialize());
  app.use(passport.session());
我做了。然后继续指定:

在典型的Web应用程序中,用于对用户进行身份验证的凭据仅在登录请求期间传输。如果验证成功,将通过用户浏览器中设置的cookie建立和维护会话。 每个后续请求都不包含凭据,而是包含标识会话的唯一cookie。为了支持登录会话,Passport将对会话进行序列化和反序列化用户实例。

passport.serializeUser(function(user, done) {
  console.log("serialize user: ", user);
  done(null, user[0]._id);
});

passport.deserializeUser(function(id, done) {
  User.findById(id, function(err, user) {
    done(err, user);
  });
});

如果我理解正确,登录后,用户应该看到正在设置的新cookie。 我的序列化和反序列化函数似乎工作。登录用户后,控制台将记录用户详细信息。控制台中没有错误消息。 但是,当我登录用户时,我没有看到任何cookie。

我是否应该手动添加其他命令?像这样的东西:

res.cookie('userid', user.id, { maxAge: 2592000000 });

我正在使用Redux,所以我应该通过reducer处理持久会话,而不是使用经过身份验证的(true或false)变量?

我认为我现在在服务器端应该完成的工作与客户端应该完成的工作之间有点混淆。

3 个答案:

答案 0 :(得分:0)

//npm modules
const express = require('express');
const uuid = require('uuid/v4')
const session = require('express-session')
const FileStore = require('session-file-store')(session);
const bodyParser = require('body-parser');
const passport = require('passport');
const LocalStrategy = require('passport-local').Strategy;

const users = [
  {id: '2f24vvg', email: 'test@test.com', password: 'password'}
]

// configure passport.js to use the local strategy
passport.use(new LocalStrategy(
  { usernameField: 'email' },
  (email, password, done) => {
    console.log('Inside local strategy callback')
    // here is where you make a call to the database
    // to find the user based on their username or email address
    // for now, we'll just pretend we found that it was users[0]
    const user = users[0] 
    if(email === user.email && password === user.password) {
      console.log('Local strategy returned true')
      return done(null, user)
    }
  }
));

// tell passport how to serialize the user
passport.serializeUser((user, done) => {
  console.log('Inside serializeUser callback. User id is save to the session file store here')
  done(null, user.id);
});

// create the server
const app = express();

// add & configure middleware
app.use(bodyParser.urlencoded({ extended: false }))
app.use(bodyParser.json())
app.use(session({
  genid: (req) => {
    console.log('Inside session middleware genid function')
    console.log(`Request object sessionID from client: ${req.sessionID}`)
    return uuid() // use UUIDs for session IDs
  },
  store: new FileStore(),
  secret: 'keyboard cat',
  resave: false,
  saveUninitialized: true
}))
app.use(passport.initialize());
app.use(passport.session());

// create the homepage route at '/'
app.get('/', (req, res) => {
  console.log('Inside the homepage callback')
  console.log(req.sessionID)
  res.send(`You got home page!\n`)
})

// create the login get and post routes
app.get('/login', (req, res) => {
  console.log('Inside GET /login callback')
  console.log(req.sessionID)
  res.send(`You got the login page!\n`)
})

app.post('/login', (req, res, next) => {
  console.log('Inside POST /login callback')
  passport.authenticate('local', (err, user, info) => {
    console.log('Inside passport.authenticate() callback');
    console.log(`req.session.passport: ${JSON.stringify(req.session.passport)}`)
    console.log(`req.user: ${JSON.stringify(req.user)}`)
    req.login(user, (err) => {
      console.log('Inside req.login() callback')
      console.log(`req.session.passport: ${JSON.stringify(req.session.passport)}`)
      console.log(`req.user: ${JSON.stringify(req.user)}`)
      return res.send('You were authenticated & logged in!\n');
    })
  })(req, res, next);
})

// tell the server what port to listen on
app.listen(3000, () => {
  console.log('Listening on localhost:3000')
})

尝试浏览链接 https://medium.com/@evangow/server-authentication-basics-express-sessions-passport-and-curl-359b7456003d

答案 1 :(得分:0)

1 检查主机名。 就我而言,cookie是在127.0.0.1而非localhost上设置的。

2 确保在express session之前调用passport session

答案 2 :(得分:0)

如果有人将 mongooseexpressjspassportjs 一起使用,您可以尝试下面的这个方法。这也会在服务器重启后保存 cookie。对于其他数据库,您可以检查 Expressjs Compatible Session Stores List

const session = require("express-session");
const MongoStore = require("connect-mongo")(session);

// before this setup mongoose connection then add this code.
app.use(
  session({
    store: new MongoStore({
      mongooseConnection: mongoose.connection,
      ttl: 365 * 24 * 60 * 60, // = 365 days.
    }),
    secret: process.env.AUTH_SECRET,
    resave: true,
    saveUninitialized: true,
    cookie: {
      secure: app.get("env") === "production",
    },
  })
);