![](/img/trans.png)
[英]Session Node.js + Passport.js + Redis, Store session by user.id
[英]How to get user.id from jwt token in Node.js?
在我的用戶控制器中,我創建了一個令牌,當他登錄到我的應用程序時,我將在其中保存該用戶的 ID。
exports.findOne = (req, res) => {
User.findOne({
where: {
login: req.body.login,
},
})
.then(user => {
if (user) {
if (bcrypt.compareSync(req.body.password, user.password)) {
const token = jwt.sign(
{
id: user.id, // this is the id I need.
},
env.SECRET_KEY,
{
expiresIn: 129600,
},
);
return res.status(200).json({
message: 'Auth successful',
token,
});
}
...
}
})
.catch(err => {
res.status(400).json({ error: err });
});
};
現在在另一個控制器中,我想讀取此 ID 並將其用於我的目的。 我怎樣才能得到它?
const loginId = '?'; // here I want to give it to id
Bill.update(
{
available_funds: available_funds - amountMoney,
},
{ where: { id_owner: loginId } },
).then(() => {
res.status(200).send(`ok`);
});
制作一個中間件,該中間件在轉發到更新路由之前會檢查傳入的令牌。 該中間件應負責驗證登錄后從客戶端代碼傳遞的傳入令牌(通常將令牌存儲在cookie中)。
現在,在您的中間件中,您可以執行以下操作:
app.use(function(req,res,next) {
JWT.verify(req.cookies['token'], 'YOUR_SECRET', function(err, decodedToken) {
if(err) { /* handle token err */ }
else {
req.userId = decodedToken.id; // Add to req object
next();
}
});
});
然后,最后在即將到來的控制器中,您可以從請求對象訪問ID:
const loginId = req.userId;
Bill.update(
{
available_funds: available_funds - amountMoney,
},
{ where: { id_owner: loginId } },
).then(() => {
res.status(200).send(`ok`);
});
您不需要添加額外的代碼。 要訪問 userId 使用這個:
req.payload.id
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.