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

后端 未结 7 1264
佛祖请我去吃肉
佛祖请我去吃肉 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:23

    res.render accepts an optional parameter that is an object containing local variables for the view.

    If you use passport and already authenticated the user then req.user contains the authenticated user.

    // app.js
    app.get('/dashboard', (req, res) => {
      res.render('./dashboard', { user: req.user })
    })
    

    // index.ejs
    <%= user.name %>
    
    0 讨论(0)
  • 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)
    })
    
    0 讨论(0)
  • 2021-02-01 14:27

    In reference to the Passport documentation, the user object is contained in req.user. See below.

        app.post('/login',
          passport.authenticate('local'),function(req, res) {
           // If this function gets called, authentication was successful.
           // `req.user` contains the authenticated user.
           res.redirect('/users/' + req.user.username);
         });
    

    That way, you can access your user object from the page you redirect to.

    In case you get stuck, you can refer to my Github project where I implemented it clearly.

    0 讨论(0)
  • 2021-02-01 14:27

    late to party but this worked for me

    use this in your app.js

    app.use(function(req,res,next){
      res.locals.currentUser = req.user;
      next();
    })
    

    get current user details in client side like ejs

    <%= locals.currentUser.[parameter like name || email] %>
    
    0 讨论(0)
  • 2021-02-01 14:30

    You can define your route this way as follows.

    router.post('/login',
    passport.authenticate('local' , {failureRedirect:'/login', failureFlash: true}),
    function(req, res) {
       res.redirect('/home?' + req.user.username);
    });
    

    In the above code snippet, you can access and pass any field of the user object as "req.user.field_name" to the page you want to redirect. One thing to note here is that the base url of the page you want to redirect to should be followed by a question mark.

    0 讨论(0)
  • 2021-02-01 14:44

    You'll need to make sure that you register a middleware that populates req.session before registering the passport middlewares.

    For example the following uses express cookieSession middleware

    app.configure(function() {
    
      // some code ...
    
      app.use(express.cookieParser());
      app.use(express.bodyParser());
      app.use(express.cookieSession()); // Express cookie session middleware 
      app.use(passport.initialize());   // passport initialize middleware
      app.use(passport.session());      // passport session middleware 
    
      // more code ...
    
    });
    
    0 讨论(0)
提交回复
热议问题