Search code examples
javascriptnode.jsexpressexpress-jwt

using jwt with express-jwt with middleware in express js


I'm trying to use express-jwt to make a middleware but it still the same problem:

app.use(expressJwt({ secret: SECRET, algorithms: ['HS256']}).unless({path: ['/login', '/']}));
        ^
TypeError: expressJwt is not a function

this is a part of my code :

const express = require('express');
const app = express();
const jwt = require('jsonwebtoken');
const expressJwt = require('express-jwt');

app.use(expressJwt({ secret: SECRET, algorithms: ['HS256']}).unless({path: ['/login', '/']}));

app.use(function (err, req, res, next) {
  if (err.name === 'UnauthorizedError') {
    res.status(401).send('Invalid token, access /login with username and password in the Body to authenticate.');
  }
}
);

app.post('/login', (req, res) => {
  if (!req.body.username || !req.body.password) {
      return res.status(400).json({ message: 'Error. Please enter the correct username and password' })
  }
  const user = users.find(u => u.username === req.body.username && u.password === req.body.password)
  if (!user) {
      return res.status(400).json({ message: 'Error. Wrong login or password' })
  }
  const token = jwt.sign({
      username: user.username,
      role: user.role
  }, SECRET, { expiresIn: '3 hours' })
  return res.json({ access_token: token })
})

Solution

  • You have to import correctly the library :

    const { expressJwt: jwt } = require("express-jwt");
    

    source: https://www.npmjs.com/package/express-jwt#usage