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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/14951789/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-02 17:12:11  来源:igfitidea点击:

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

node.jsexpress

提问by kurisukun

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!

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

采纳答案by 250R

You'll need to make sure that you register a middlewarethat populates req.sessionbefore registering the passport middlewares.

你需要确保你注册一个中间件用于填充req.session登记护照中间件之前。

For example the following uses express cookieSession middleware

例如下面使用express 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 ...

});

回答by Darcys22

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

聚会迟到了,但我自己在谷歌上搜索了答案后发现这个问题没有得到解答。

Inside the request will be a req.userobject 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});
    }

回答by L.T

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 projectwhere I implemented it clearly.

万一遇到问题,可以参考我的 Github 项目,我在那里清楚地实现了它。

回答by Sajeed786

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.

在上面的代码片段中,您可以访问用户对象的任何字段并将其作为“req.user.field_name”传递到要重定向的页面。这里要注意的一件事是,您要重定向到的页面的基本 url 后面应该跟一个问号。

回答by DarkLite1

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

我对 javascript 还很陌生,但正如我从教程中所了解的那样,您必须首先实现一些会话,middleware如 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)
})

回答by Hasan Sefa Ozalp

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

res.render接受一个可选参数,该参数是一个包含视图局部变量的对象。

If you use passportand already authenticated the user then req.usercontains the authenticated user.

如果您使用通行证并且已经通过用户身份验证,则req.user包含经过身份验证的用户。

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


// index.ejs
<%= user.name %>