Passport.js: how to access user object after authentication?

后端 未结 7 1255
佛祖请我去吃肉
佛祖请我去吃肉 2021-02-01 14:01

I\'m using Passport.js to login a user with username and password. I\'m essentially using the sample code from the Passport site. Here are the relevant parts (I think) of my c

7条回答
  •  一向
    一向 (楼主)
    2021-02-01 14:24

    I'm pretty new to javascript but as I understand it from the tutorials you have to implement some session middleware first as indicated by 250R.

    const session = require('express-session')
    const app = express()
    
    app.use(bodyParser.urlencoded({ extended: false }))
    app.use(bodyParser.json())
    
    let sess = {
        genid: (req) => {
            console.log('Inside the session middleware')
            console.log(req.sessionID)
            return uuid()
        },
        store: new FileStore(),
        secret: 'keyboard cat', // password from environment
        resave: false,
        rolling: true,
        saveUninitialized: true,
        cookie: {
            HttpOnly: true,
            maxAge: 30 * 60 * 1000 // 30 minutes
        }
    }
    
    app.use(session(sess))
    
    // call passport after configuring the session with express-session
    // as it rides on top of it
    app.use(passport.initialize())
    app.use(passport.session())
    
    // then you will be able to use the 'user' property on the `req` object
    // containing all your session details
    app.get('/test', function (req, res) {
        console.log(req.user)
    })
    

提交回复
热议问题