Search code examples
node.jsexpressjwtexpress-jwt

difference between using jwt


Question 1: What's the difference between the first approach and the second one

Question 2: what are the use case for both of them?

jwtMW:

const jwtMW = exjwt({
  secret: "keyboard cat 4 ever",
  algorithms: ["HS256"],
  credentialsRequired: true,
});

approach one

router.post("/authRequest", jwtMW, async (req, res) => {
  let toeken = req.headers.authorization;
  // use the decoded infomation for further verification
});

approach two

router.post("/authRequest2", async (req, res) => {
  const reqToken = req.headers.authorization.split(" ")[1];
  const secret = "keyboard cat 4 ever";
  var decoded = jwt.verify(reqToken, secret);
  // use the decoded infomation for further verification
});

Thanks in advance.


Solution

  • first approach is incorrect, because after path in route you can using middleware, but jwtMW is not middleware, if you want use a middleware try like this:

    check-auth.js

    const jwt = require('jsonwebtoken');
    module.exports = (req, res, next) => {
      try {
        const token = req.headers.authorization.split(' ')[1]; // Authorization: 'Bearer TOKEN'
        if (!token) {
          throw new Error('Authentication failed!');
        }
        const decodedToken = jwt.verify(token, 'supersecret_dont_share');
        req.userData = { userId: decodedToken.userId };
        next();// it's important line
      } catch (err) {
        throw new Error('Authentication failed!');
      }
    };
    
    

    after that require middleware in route file

    const checkAuth = require('../middleware/check-auth');//it's a exmple
    
    router.post('/authRequest', checkAuth  , async (req, res) => {
           // do somethings
    });
    

    in the second approach you don't use a middleware