Lester_27
Lester_27

Reputation: 3

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 })
})

Upvotes: 0

Views: 228

Answers (2)

Anisha Yadav
Anisha Yadav

Reputation: 1

According to the documentations will need to change the module. Use this 'expressjwt' in place of 'expressJwt'.

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

Upvotes: 0

Suleyman
Suleyman

Reputation: 262

You have to import correctly the library :

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

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

Upvotes: 0

Related Questions