Question:
I'm following the following tutorial to create an authentication system using Node.js and JWT: https://scotch.io/tutorials/authenticate-a-node-js-api-with-json-web-tokens
Following the tutorial steps, I can verify that the user is correct and create the JWT. But apparently the token isn't being stored anywhere. When accessing the /test route, nothing is returned. Here's 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;
Answer:
The token
is not saved. In a request you will need to inform it, usually by headers
, but it can be wherever you want.
The server will receive the token
and will validate it with the private key . Thus, you have the validated token
data.