Home > other >  Unauthorized Error when I want to delete article with authentification (jwt)
Unauthorized Error when I want to delete article with authentification (jwt)

Time:05-09

I've created a route called login and another one function(middleware), if the authentication is good, this can be redirected to the delete route but unfortunately, my jwt token is not recognizable.

I want to know why, the problem must be in this part of api :

Api


  function parseArticle (req, res, next) {



let token = req.headers['x-access-token'] || req.headers['authorization'];
if (!!token && token.startsWith('Bearer ')) {
  token = token.slice(7, token.length);
}

if (token) {
  jwt.verify(token, 'RANDOM_TOKEN_SECRET', (err, decoded) => {
    if (err) {
      return res.status(401).json('token_not_valid');
    } else {
      req.decoded = decoded;

      const expiresIn = 24 * 60 * 60;
      const newToken  = jwt.sign({
            user : decoded.user
          },
          'RANDOM_TOKEN_SECRET',
          {
            expiresIn: expiresIn
          });


      next();
    }
  });
} else {
  return res.status(401).json('token_required');
}



}

router.route('/article/:articleId')

.get(parseArticle, (req, res) => {
  
  db.query("SELECT *  FROM articles WHERE id_article = (?)", [req.articleId], function (err,result) { if (err) throw err;
    console.log(result);
    res.json(result)
  })

})


.put(parseArticle, (req, res) => {
  const name = req.body.name
  const description = req.body.description
  const image = req.body.image
  const price = parseInt(req.body.price)

  req.article.name = name
  req.article.description = description
  req.article.image = image
  req.article.price = price
  res.send()
})

.delete(parseArticle, (req, res) => {

  db.query("DELETE FROM articles WHERE id_article = (?)", [req.articleId], function (err,result) { if (err) throw err;
    console.log(result);})

res.json({message: "Propre"})})

router.post('/login', (req, res) => {
function runQuery(sqlQuery, args){
  return new Promise(function (resolve, reject) {
    db.query(sqlQuery, args, function(error, results, fields) {
      if (error) reject(error);
      else resolve(results);
    });
  });
}

runQuery("SELECT * from users where email = ? ", [req.body.email]).then(user => {
  if (user.length === 0) {
    return res.status(401).json({ error: 'Utilisateur non trouvé !',
      success : 0});
  }
  bcrypt.compare(req.body.password, user[0].password)
      .then(valid => {
        if (!valid) {
          return res.status(401).json({ error: 'Mot de passe incorrect !',
            success : 0});
        }


        const userId = user[0].id_user;
        const token = jwt.sign({ userId: user[0].id_user },
            'RANDOM_TOKEN_SECRET',
            { expiresIn: '24h' });
        res.header("Authorization","Bearer "   token)

        return res.status(200).json({success : 1})
      })

      .catch(error => res.status(500).json({ error }));

})
    .catch(error => res.status(500).json({ error }));
});

Login.vue

<template>

<form @submit.prevent="checkData">
  <input type="text" name="email" v-model="login.email" placeholder="Entrez votre adresse-mail"/>
  <input type="text" name="password" v-model="login.password" placeholder="Entrez votre mot de passe"/>
  <button type="submit"> Connexion </button>
</form>

</template>

<script>

module.exports = {
  name: "Login",

  data () {
    return {
      login : {
        email: "",
        password: "",
      },
    }
  },

  methods : {
     async checkData() {
       let user = {email : this.login.email, password : this.login.password}

      try {
        const response = await axios.post('/api/login', user)
        console.log(response.data.success)
        if(response.data.success === 1){
          await this.$router.push({name: 'home'})
        }
        if(response.data.success === 0){
          this.error = "Connexion Échouée"
        }

      }
      catch(err) {console.error("network error",err)}
    }
  }
}


</script>

<style scoped>
button {
  padding: 10px;
}
</style>

Thanks for you help,

Have a nice week-end

CodePudding user response:

You return the token to the client in the Authorization header:

res.header("Authorization","Bearer "   token)

This is a non-standard use of this header, it will not automatically be sent back in the next request. At the least, you would need extra code on the client to receive this header and store the token, for example, in the session storage.

It's probably easier to store the token in a session cookie, which will be handled automatically by the client:

res.cookie("token", token, {httpOnly: true})

Also consider the secure option for the cookie. You must also extend your server-side code to find the token in the cookie:

let token = req.headers['x-access-token'] || req.headers['authorization']
  || req.cookies.token;
  • Related