Home > Software design >  Token doesn't save in header Jsonwebtoken
Token doesn't save in header Jsonwebtoken

Time:08-31

I tried to make a a sign up and a login authorization, but the token doesn't save in the header, resulting undefined by trying to get it. This is the code:

import {Usuario} from '../models/Usuario.js';
import bcrypt from 'bcryptjs';
import jwt from 'jsonwebtoken';


export const registrarUsuario = async (req, res) => {
    try{
        const {run, nombre, password, rol} = req.body;
        const passwordHash = await bcrypt.hash(password, 10);
        const usuario = await Usuario.create({
            run,
            nombre,
            password: passwordHash,
            rol
        })
        const token = jwt.sign({run: usuario.run, rol: usuario.rol}, "mi_clave_secreta", {
            expiresIn: 120
        });
        res.json({
            auth: true,
            token: token
        });
    } catch (error) {
        return res.status(500).json({message: error.message});
    }
}

export const loginUsuario = async (req, res) => {
    try{
        const {run, password} = req.body;
        const usuario = await Usuario.findByPk(run);
        if(usuario){
            const validPassword = await bcrypt.compare(password, usuario.password);
            if(validPassword){
                const token = jwt.sign({run: usuario.run, rol: usuario.rol}, "mi_clave_secreta", {
                    expiresIn: 120
                });
                res.json({
                    auth: true,
                    token: token
                });
            } else {
                return res.status(401).json({message: 'Contraseña incorrecta'});
            }
        } else {
            return res.status(404).json({message: 'Usuario no está registrado'});
        }
    } catch (error) {
        return res.status(500).json({message: error.message});
    }
}

export const paginaProtegida = (req, res, next) => {
    const bearerHeader = req.headers['authorization'];
    console.log(bearerHeader);
}

And using the paginaProtegida, the console throws the bearerHeader as Undefined. Any help is good, please.

CodePudding user response:

In login and signup requests, response contains token, and in authorized routes you have to provide in request headers, below provided key pair: Authorization: Bearer value-from-login-responded-token.

CodePudding user response:

You are returning the token in the body of both register and login methods. In your client, you need to get the token, and put it in the headers of the HTTP request you want to send to your API.

In your API method paginaProtegida, you are getting the token from the authorization header (not Authorization, be aware of the caps): const bearerHeader = req.headers['authorization'];. So, your client should write the token in the request using the same header name.

If you want to properly use a Bearer token (Bearer Authentication), it is recommended that you follow this format:

  • In the client, add a header with name Authorization (capital A). Add the token value as: Bearer your-token.
  • In your server, get the header: const bearerHeader = req.headers['Authorization']; and get the token from the bearerheader (You can use a function like the one provided in this thread):
export const parseBearer = (bearer) => {
  const [_, token] = bearer.trim().split(" ");
  return token;
};
  • Related