R
R
Ramil992016-11-09 15:57:13
MongoDB
Ramil99, 2016-11-09 15:57:13

What data needs to be written to jwt (node.js + mongo)?

To generate a token I use

jwt     = require('jsonwebtoken');
/* далее какой-то код */

//функция для создания токена
function createToken(user) {
  return jwt.sign(user, config.secret, { expiresIn: 60*60*5 });
}

/* далее какой-то код */

//после регистрации/авторизации ( в случае успеха) вызывается функция для создания токена
createToken(user);

I would like to know the best practice, what data needs to be passed to the function to create the token .
Will it be, for example, login (John) and id( ObjectId("5821d94dbb021a1360582da3") in the case of MongoDB)?
And, here, I think, the question will be relevant:
After I have some information stored in the token that allows me to initialize the user, I can pull out his data from the database. Is it correct to initialize user based on jwt? For initialization, I use the express-jwt lib , which, if successful, sets req.user?
Thank you.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
M
Maxim, 2016-11-09
@Ramil99

You don't need to put your login into the token. The token should not contain "personal information", but ObjectId is already possible. This does not fit "personally", because by 5821d94dbb021a1360582da3 you can not find out something about the user if your database has not been stolen (I could be wrong).
Just in case, I will give the full code of the route with the issuance of a token, if it is not particularly useful to you, then someone can scold me, since I am not strong in the backend. The code is not on promises, but on callbacks (as in ancient times). This is bad. With the help of promises, the code will be "flatter" and easier to maintain.

const express = require('express')
const router = express.Router()
const User = require('../models/user')
const v4 = require('node-uuid').v4
const jwt = require('jsonwebtoken')

router.post('/signup', (req, res, next) => {

  req.check('email', 'Please enter a valid email').len(1).isEmail()
  req.check('password', 'Please enter a password with a length between 4 and 34 digits').len(4, 34)

  const errors = req.validationErrors()

  if (errors) {
    return res.status(400).json({ errors })
  } else {
    User.hashPassword(req.body.password, (err, passwordHash) => {
      if (err) {
        return res.status(400).json({ error: err.message })
      }

      const user = new User({
        name: req.body.name,
        nickname: req.body.nickname,
        email: req.body.email,
        password: req.body.password,
      })

      user.passwordHash = passwordHash
      user.save((err, item) => {
        if (err) {
          return res.status(400).json({ error: err.message })
        }
        const payload = {
          _id: item._id,
          iss: 'http://localhost:3000',
          permissions: 'poll',
        }
        const options = {
          expiresIn: '7d',
          jwtid: v4(),
        }
        const secret = new Buffer(process.env.AUTH0_CLIENT_SECRET, 'base64')
        jwt.sign(payload, secret, options, (err, token) => {
          return res.json({ data: token })
        })
      })
    })
  }
})

router.post('/signin', (req, res, next) => {

  req.check('email', 'Please enter a valid email').len(1).isEmail()
  req.check('password', 'Please enter a password with a length between 4 and 34 digits').len(4, 34)

  const errors = req.validationErrors()
  const password = req.body.password

  if (errors) {
    return res.status(400).json({ errors })
  } else {
    User.findOne({ email: req.body.email }, (err, user) => {
      if (err) {
        return res.status(400).json({ error: err.message })
      }
      if (!user) {
        return res.status(400).json({ error: 'User not found' })
      }
      User.comparePasswordAndHash(password, user.passwordHash, (err, areEqual) => {
        if (err) {
          return res.status(400).json({ error: err.message })
        }
        if (!areEqual) {
          return res.status(400).json({ error: 'Wrong password' })
        }
        const payload = {
          _id: user._id,
          iss: 'http://localhost:3000',
          permissions: 'poll',
        }
        const options = {
          expiresIn: '7d',
          jwtid: v4(),
        }
        const secret = new Buffer(process.env.AUTH0_CLIENT_SECRET, 'base64')
        jwt.sign(payload, secret, options, (err, token) => {
          return res.json({ data: token })
        })
      })
    })
  }
})

module.exports = router;

In the future, a piece of payload:
const payload = {
          _id: item._id,
          iss: 'http://localhost:3000',
          permissions: 'poll',
        }

can be "decoded" directly on the client, which is very convenient.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question