簡體   English   中英

Node.js JWT,從token獲取user_id

[英]Node.js JWT, get user_id from token

強文本我正在構建 node.js + mongodb rest api。 我使用 jwt 用戶身份驗證,但遇到問題。 我需要獲取經過身份驗證的用戶(user_id,名稱)的詳細信息,認為可以從令牌中獲取它們,但我不知道該怎么做。 這怎么可能呢?

更新

我正在做一個帖子請求

router.route('/articles')

  .post(function (req, res) {

      var article= new Article();      
      article.user_id = ???; // here needs user_id
      article.imdb_id = req.body.imdb_id;
      article.title = req.body.title;
      article.thumb = req.body.thumb;

      article.save(function(err) {
          if (err)
              res.send(err);

          res.json({ message: 'Added' });
      });

  });

我需要插入文章集合作者 ID (user_id),但我不知道如何獲取經過身份驗證的 user_id。

試圖這樣做:

  var token = req.body.token || req.query.token || req.headers['x-access-token'];

  if (token) {
    jwt.verify(token, app.get('superSecret'), function(err, decoded) {      
      if (err) {
        return res.json({ success: false, message: 'Failed to authenticate token.' });    
      } else {
        req.decoded = decoded;
        console.log(decoded);
        next();
      }
    });

已解碼返回有關用戶的所有信息(名稱、密碼、_id)。 是否可以從這里只獲取 user_id 和 name?

當您簽署JSON Web令牌時,您可以將其傳遞給用戶對象。 在這里,您可以存儲您需要的任何用戶數據。 然后對該對象進行簽名和編碼,並將其設置為令牌。 當您向API傳遞請求時,如果JWT有效,則驗證函數應將此用戶對象返回給您。

我喜歡使用Hapi框架來創建我的Restful API,所以我將使用Hapi給出一個例子。

在server.js文件中,您需要注冊hapi-auth-jwt2包:

server.register(require('hapi-auth-jwt2'), (err) => {
    if (err) {
        throw err;
    }

    server.auth.strategy('jwt', 'jwt', {
        key: config.jwt.secret,
        validateFunc: auth.validate,
        verifyOptions: { algorithms: ['HS256'] }
    });

    server.auth.default('jwt');
});

你的驗證功能:

export default {
    validate: (tokenObject, req, callback) => {
        validateToken(tokenObject.user_id, (err, user) => {
            if (err) {
                callback(Boom.unauthorized('User is unauthorized.'), false);
            } else {
                req.user = user;
                callback(null, true);
            }
        });
    }
};

validateToken函數應該使用您從令牌獲取的用戶ID並查詢該用戶。 如果找到用戶,則表示您知道該令牌有效,您可以返回並存儲其余的用戶信息。

要創建令牌,我使用“jsonwebtoken”包:

generateToken: (user_id, name, callback) => {
    'use strict';
    callback(null, JWT.sign({
        user_id: user_id,
        name: name
    }, config.JWT.SECRET, {
        expiresIn: 86400
    }));
}

假設您需要驗證從用戶發送的令牌是否已經在您的數據庫中的標頭中(我們將其稱為protect

const {promisify} = require('util');
const jwt = require('jsonwebtoken');
const User = require('./../models/userModel');

...

exports.protect = catchAsync(async(req, res, next) => {
// 1) Getting token and check if it's there in headers
let token;

//authorization is the name of the header token
if (req.headers.authorization) {
    token = req.headers.authorization;
}


if (!token) {
    return next(new AppError('You are not logged in! Please Login To get Access.', 401));
}

// 2) Verification Token is a valid token
const decoded = await promisify(jwt.verify)(token, process.env.JWT_SECRET);
// WE CAN GET THE USER ID FROM DECODED




// 3) Check if user still exists not deleted
const currentUser = await User.findById(decoded.id);
if (!currentUser) {
    return next(new AppError('the user does not exist.', 401));
}else{
// WHAT EVER YOU WANT TO DO AFTER CHECKING USER FOUND IN DATABASE

})

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM