Search code examples
node.jsapiauthenticationtokenmiddleware

Create a token Authentication for my restfull api in NodeJS


How is the best way to create a token auth in nodejs for access to api by front-end application?


Solution

  • If you have to create a authentication token you can refer JWT-Token:

    Token Creation:

     const token = jwt.sign({username},'my_secret_key',{ expiresIn: 60*60*24 });
          res.json({
            "success":true,
            "data":data,
            "token":token
          });
    

    Token verification:

    const jwt = require('jsonwebtoken');
    
    module.exports = function checkToken(req, res, next) {
        var token = req.headers['token'];
        if(token) {
          jwt.verify(token, 'my_secret_key',(err,decode)=>{
            if(err) {
              res.json({"status":500,
                "message":"INVALID TOKEN",
                "error":err.message
             });
           } else {
              next();
            }
          })
        } else {
          res.json({"status":500,
          "message":"NO TOKEN PROVIDE",
          "error":"token must be provide in header for endpoint access"
       });
        }
      }
    

    You can refer link here