Passport.js:验证后如何访问用户对象?

时间:2021-12-30 01:23:32

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 code:

我正在使用Passport.js以用户名和密码登录用户。我基本上使用Passport站点的示例代码。以下是我的代码的相关部分(我认为):

app.use(passport.initialize());
app.use(passport.session());

passport.serializeUser(function(user, done) {
    done(null, user);
});

passport.deserializeUser(function(obj, done) {
    done(null, obj);
});

passport.use(new LocalStrategy(function(username, password, done) {
    User.findOne({ username: username }, function(err, user) {
        if (err) {
            return done(err);
        }
        if (!user) {
            return done(null, false, { message: 'Incorrect username.' });
        }
        if (!user.validPassword(password)) {
            return done(null, false, { message: 'Incorrect password.' });
        }
        return done(null, user);
        });
    }
));

app.post('/login',
    passport.authenticate('local', { failureRedirect: '/login/fail', failureFlash: false }),
    function(req, res) {
        // Successful login
        //console.log("Login successful.");
        // I CAN ACCESS req.user here
});

This seems to login correctly. However, I would like to be able to access the login user's information in other parts of the code, such as:

这似乎正确登录。但是,我希望能够在代码的其他部分访问登录用户的信息,例如:

app.get('/test', function(req, res){
    // How can I get the user's login info here?
    console.log(req.user);  // <------ this outputs undefined
});

I have checked other questions on SO, but I'm not sure what I'm doing wrong here. Thank you!

我已经检查了其他问题,但我不确定我在这里做错了什么。谢谢!

3 个解决方案

#1


5  

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

在注册护照中间件之前,您需要确保注册填充req.session的中间件。

For example the following uses express cookieSession middleware

例如,以下使用表达cookieSession中间件

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 ...

});

#2


44  

Late to the party but found this unanswered after googling the answer myself.

晚到了聚会,但在我自己搜索答案后发现这个没有答案。

Inside the request will be a req.user object that you can work withr.

请求内部将是一个req.user对象,您可以使用它。

Routes like so:

这样的路线:

app.get('/api/portfolio', passport.authenticate('jwt', { session: false }), stocks.buy);

Controller like this:

这样的控制器:

buy: function(req, res) {
      console.log(req.body);
      //res.json({lel: req.user._id});
      res.json({lel: req.user});
    }

#3


2  

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

参考Passport文档,用户对象包含在req.user中。见下文。

    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.

如果你遇到困难,你可以参考我的Github项目,我清楚地实现了它。

#1


5  

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

在注册护照中间件之前,您需要确保注册填充req.session的中间件。

For example the following uses express cookieSession middleware

例如,以下使用表达cookieSession中间件

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 ...

});

#2


44  

Late to the party but found this unanswered after googling the answer myself.

晚到了聚会,但在我自己搜索答案后发现这个没有答案。

Inside the request will be a req.user object that you can work withr.

请求内部将是一个req.user对象,您可以使用它。

Routes like so:

这样的路线:

app.get('/api/portfolio', passport.authenticate('jwt', { session: false }), stocks.buy);

Controller like this:

这样的控制器:

buy: function(req, res) {
      console.log(req.body);
      //res.json({lel: req.user._id});
      res.json({lel: req.user});
    }

#3


2  

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

参考Passport文档,用户对象包含在req.user中。见下文。

    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.

如果你遇到困难,你可以参考我的Github项目,我清楚地实现了它。