2

I tried to implement jwt token generation in node js.I got jwt token but how to validate token using node js crud operation.but I got token jwt verfiy code using callback function.without call back function used to implement async/awit function implement.

index.js

router.post('/', async (req, res) => {
    (async function() {
        try {
          await client.connect();
          console.log("Connected correctly to server");
          const db = client.db('olc_prod_db');

          //Validation
          const { error } = validate.validate(req.body);
          if (error)
          {
            return res.status(400).send(error.details[0].message);
          }
          else
          {
            const check_login = req.body
            const r = await db.collection('UserRegistration').find().toArray();
            r.forEach(element => {
                if(element['username'] == check_login['username'])
                {
                    const token = get_token.validate(req.body)
                    res.send({"token ":token})
                }
                else 
                {
                    return res.send(401,"Un Authorized");
                }
            });

          }
          client.close();
        } catch(err) {
          console.log(err.stack);
        }
      })();

  });

authtoken.js

var jwt = require('jsonwebtoken')
function get_token(userdata)
{

    var accessToken = jwt.sign(userdata, 'secretkey', {
        //Set the expiration
        expiresIn: 3600 //we are setting the expiration time of 1 hr. 
    });
    //send the response to the caller with the accesstoken and data
    console.log('Authentication is done successfully.....');
    return accessToken

}





exports.validate = get_token;
smith hari
  • 437
  • 1
  • 11
  • 22
  • token validation using jwt in node should be done in middlewares.. in that case it would handle your validation on every request.. for more detail visit https://github.com/m-nathani/node-typescript-starter – Murtaza Hussain Apr 25 '19 at 08:33
  • can give me code jwt veriify token without using callback function using async and awit function – smith hari Apr 25 '19 at 08:44
  • 1
    Verify token is just `jwt.verify( accessToken, 'secretkey' );`, no need for async/await. – Wiktor Zychla Apr 25 '19 at 08:50
  • https://github.com/m-nathani/node-typescript-starter/blob/master/src/middleware/auth.ts check this out for auth middleware, and https://github.com/m-nathani/node-typescript-starter/blob/master/src/controller/general.ts for login calls.. – Murtaza Hussain Apr 25 '19 at 09:33
  • please upvote the answer if that was helpfull. – Murtaza Hussain Apr 25 '19 at 09:35
  • I have doubt I tried this (jwt.verify( accessToken, 'secretkey' ); its working fine.but how to check error msg with one condition.Invalid token or Jwt must be provided. – smith hari Apr 25 '19 at 10:17
  • i have added a error middleware too.. so if any exception occurs it will be caught up on the error middleware... – Murtaza Hussain Apr 25 '19 at 12:42

2 Answers2

3
const jwt  = require('jsonwebtoken')
const config = require('../../config/default')

function verifyjwt(req,res,next){
    const token = req.headers['authorization']
    if(!token) return res.status(401).json('Unauthorize user')

   try{
        const decoded = jwt.verify(token,config.secret);
        req.user = decoded
        next()

   }catch(e){
    res.status(400).json('Token not valid')
   }
}

module.exports = verifyjwt
Desai Ramesh
  • 131
  • 1
  • 3
1
const CONST = require('../../config')
exports.validJWTNeeded = (req, res, next) => {
    if (req.headers['authorization']) {
        try {
            let authorization = req.headers['authorization'].split(' ');
            if (authorization[0] !== 'Bearer') {
                return res.status(401).send('invalid request'); //invalid request
            } else {
                req.jwt = jwt.verify(authorization[1], CONST.SECRET);
                return next();
            }
        } catch (err) {
            return res.status(403).send(); //invalid token
        }
    } else {
        return res.status(401).send('invalid request');
    }
}
anonystick
  • 362
  • 1
  • 9
  • 2
    Bearer checking is not required and its adding lot of noise to your code, since jwt.verify will already do it for you. – Anirudha Apr 02 '20 at 08:29