Where does JWT store the tokens?

3

I'm following the following tutorial to create an authentication system using Node.js and JWT: link

Following the steps in the tutorial, I can verify that the user is correct and create JWT. However, the token is apparently not being stored anywhere. When accessing the route / test, nothing is returned. Here is the code:

const express = require('express');
const jwt = require('jsonwebtoken');

const router = express.Router();

const Usuario = require('../models/Usuario');

router.get('/teste', (req, res) => {
  const token = req.body.token || req.query.token || req.headers['x-access-token'] || null;
  return res.json(token);
});

router.post('/login', (req, res) => {
  Usuario.findOne({ email: req.body.email, senha: req.body.senha }, (err, usuario) => {
    if (err) return res.json({ error: err });
    if (!usuario) return res.json({ error: 'Email e/ou senha incorretos!' });

    jwt.sign(usuario, 'secret', { expiresIn: 3600 }, (err, token) => {
      if (err) return res.json({ error: err });
      return res.json({ message: 'Logado com sucesso!', token: token });
    });
  });
});

module.exports = router;
    
asked by anonymous 29.07.2016 / 00:52

4 answers

1

The token is not saved. In a request you will need to inform it, usually by headers , but it can be anywhere you want.

The server will receive token and will validate with the private key . So you have the validated data of token .

    
16.12.2016 / 15:17
1

The JSON Web Token (JWT) only defines a protocol and access tokens exchange format - storage is not part of the specification. Translation of the Wikipedia article :

  

[...] is an open standard based on JSON (RFC 7519) to create access tokens that claim a certain number of claims. [...] Tokens are designed to be compact, URL-safe and usable especially in the context of single-web browser (SSO) logon. JWT claims can typically be used to pass identity of authenticated users between an identity provider and a service provider, or any other type of claims as required by business processes. Tokens can also be authenticated and encrypted.

The storage of these tokens should then be explicitly implemented. There are several ways, and the choice will depend on your model. Some examples here: 1 , 2 , 3 .

    
16.12.2016 / 17:00
0

Hello, just go to the Header of your request. As you are using the name 'x-access-token'.

Using jQuery:

$.ajax({
   url : 'api/route',
   headers: {
        'x-access-token' : token
   });

Then your authentication middleware will receive this token and will validate so that you can get the payload later on in the method;)

    
21.02.2017 / 12:41
0

You can store in LocalStorage, when you make the AJAX request on the client.

    
29.08.2018 / 16:01