gpt4 book ai didi

node.js - Node js jwt如何将 token 传递给其他路由以稍后检查登录的用户信息

转载 作者:太空宇宙 更新时间:2023-11-04 00:18:14 25 4
gpt4 key购买 nike

我正在创建一个自学应用程序。因此,目前我需要使用 jsonwebtoken 对用户进行身份验证,并且我知道如何创建 token 来对用户进行身份验证。所以实际上我需要知道如何使用用户登录系统时创建的 token 来检索登录用户的信息。我到处寻找好的答案,但找不到好的答案

apiRoutes.post('/authenticate', function(req, res) {

// find the user
User.findOne({
name: req.body.name
}, function(err, user) {

if (err) throw err;

if (!user) {
res.json({ success: false, message: 'Authentication failed. User not found.' });
} else if (user) {

// check if password matches
if (user.password != req.body.password) {
res.json({ success: false, message: 'Authentication failed. Wrong password.' });
} else {

// if user is found and password is right
// create a token
var token = jwt.sign(user, app.get('superSecret'));

// return the information including token as JSON
res.json({
success: true,
message: 'Enjoy your token!',
token: token
});
}
}
});
});

这是用户登录和 token 创建过程

如果用户登录系统并创建 token ,下面的路由器我需要检索所有用户信息

apiRoutes.get('/users', function(req, res) {
if(!loggedinUser){
//throw err
}
else {
User.find({}, function(err, users) {
res.json(users);
});
});
}

所以请帮助我理解这一点,我希望你们为我这个问题提供一个好的答案

谢谢

最佳答案

生成授权 token 后,您需要通过客户端在所有请求中发送该 token 。在服务器端,您需要实现一个身份验证中间件,在此您将检查身份验证 token 。并进一步处理该请求检查此链接 How to use the middleware to check the authorization before entering each route in express?

关于node.js - Node js jwt如何将 token 传递给其他路由以稍后检查登录的用户信息,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45780155/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com