vincent05996
vincent05996

Reputation: 171

Node JS : Can't access to req.headers.authorization to extract JWT token

Hello I am trying to extract the JWT token from the Headers of my request, but this request does not contain an "Authorization" key with "Bearer xxxxx". I tried adding query parameters but it doesn't change anything ...

The goal is to create an authentication system with JWT. (I am a beginner)

The request :

  const signup = async (e) => {
    e.preventDefault();
    await POST(ENDPOINTS.USER_SIGNUP, userSignup );
  };

  const login = async (e) => {
    e.preventDefault();
    await POST(ENDPOINTS.USER_LOGIN, userLogin);
  };

In my controllers file :

exports.signup = async (req, res, next) => {
  // ====== Password encryption =========
  const saltRounds = 10;
  const { user_password: password } = req.body;
  const encryptedPassword = await bcrypt.hash(password, saltRounds);
  // ====================================
  const user = {
    ...req.body,
    user_password: encryptedPassword,
  };
  const sql = "INSERT INTO users SET ?";
  const query = db.query(sql, user, (err, result) => {
    if (err) throw err;
    console.log(result);
  });
};

exports.login = (req, res, next) => {
  //===== Check if user exists in DB ======
  const { user_email, user_password: clearPassword } = req.body;
  let sql = `SELECT user_password, user_id FROM users WHERE user_email=?`;
  db.query(sql, [user_email], async (err, results) => {
    console.log(results);
    console.log(req.body);
    if (err) {
      return res.status(404).json({ err });
    }

    // ===== Verify password with hash in DB ======
    const { user_password: hashedPassword, user_id } = results[0];
    try {
      const match = await bcrypt.compare(clearPassword, hashedPassword);
      if (match) {
        console.log("match ... user_id : ", user_id);

        // If match, verify JWT token
        res.status(200).json({
          user_id: user_id,
          token: jwt.sign({ userId: user_id }, "TOOOKEN", {
            expiresIn: "24h",
          }),
        });
      } else {
        console.log("not match");
      }
    } catch (err) {
      return res.status(400).json({ err: "une erreur" });
    }
  });
};

The middleware which will be the first code executed in my "routes" file to verify that the request has the correct token before being executing :

const jwt = require("jsonwebtoken");
require("dotenv").config();

module.exports = (req, res, next) => {
  try {
    console.log(req.headers);
    const token = req.headers.authorization.split(" ")[1];
    const decodedToken = jwt.verify(token, process.env.JWT_TOKEN);
    const userId = decodedToken.user_id;
    if (req.body.user_id && req.body.user_id !== userId) {
      throw "Invalid user ID";
    } else {
      next();
    }
  } catch {
    res.status(401).json({
      error: new Error("Invalid user ID"),
    });
  }
};

If i console.log(req.headers) :

{
  host: 'localhost:4200',
  connection: 'keep-alive',
  accept: 'application/json, text/plain, */*',
  'user-agent': 'Mozilla/5.0 (Linux; Android 6.0; Nexus 5 Build/MRA58N) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/93.0.4577.63 Mobile Safari/537.36',
  'sec-gpc': '1',
  origin: 'http://localhost:3000',
  'sec-fetch-site': 'same-site',
  'sec-fetch-mode': 'cors',
  'sec-fetch-dest': 'empty',
  referer: 'http://localhost:3000/',
  'accept-encoding': 'gzip, deflate, br',
  'accept-language': 'fr-FR,fr;q=0.9,en-US;q=0.8,en;q=0.7',
  'if-none-match': 'W/"16a8-wyX3X/tr0d8x80MrYm6LBzAWEXg"'
}

If someone know how i can retrieve the token il the "authorization" key, it will be awesome !

Upvotes: 0

Views: 2687

Answers (1)

VasanthThoraliKumaran
VasanthThoraliKumaran

Reputation: 71

If you wish, You can try axios as your HTTP client which can prevent mistakes. You can modify headers easily this way,

const instance = axios.create({
  baseURL: 'https://some-domain.com/api/',
  headers: {
      'Authorization': 'Bearer <token>',
      'X-Custom-Header': 'foobar'
    }
});

// Send a POST request
instance.post<T>('/api', {
  data, { configOptions }
});

check here https://github.com/axios/axios

Upvotes: 1

Related Questions