3
I am 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
By following the steps of the tutorial, I can verify that the user is correct and create JWT. However, apparently, the token is not being stored anywhere. When accessing the /test route, nothing is returned. Follow 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;
You are sending jwt as in your request?
– Vinicius Zaramella
I’m not sending JWT to the request, I thought the Sign method would do it automatically. How can I pass that token forward via headers, so, Vinicius?
– André
You get the token in Sign’s reply in, you have to pick up that token and store it somewhere. If your customer is a browser, it can.ser in cookies for example. Ai how to add the header will depend on the client you are using to make the request.
– Vinicius Zaramella
I get it. In case, I would like to not use cookies for this, how can I pass this token by header x-access-token?
– André
In the case of Postman vc you must add an x-access-token header in the request configuration.
– Vinicius Zaramella