I am trying to authenticate the nodejs api's using passport-jwt authentication strategy, but it always throws 401 unauthorized error. I tried various implementations but passport.authenticate function just doesn't seem to work.
Using below passport versions:
"passport": "^0.4.0",
"passport-jwt": "^4.0.0",
Please see my code below:
Tried below options:
jwtFromRequest: ExtractJwt.fromAuthHeaderAsBearerToken()
jwtFromRequest: ExtractJwt.fromHeader('authorization')
jwtFromRequest: ExtractJwt.fromAuthHeaderWithScheme('Bearer')
jwtFromRequest: ExtractJwt.fromAuthHeaderWithScheme('jwt')
But not working.
Tried looking into passport-jwt 401 Unauthorized and other links for reference as well.
app.js file:
const express = require('express');
const bodyParser = require('body-parser');
const passport = require('passport');
const cors = require('cors');
const app = express();
const login = require('./routes/login');
app.use(cors());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());
// app.use(passport.initialize());
app.use('/', login);
app.listen(8000, () => console.log('Server running on http://localhost:8000/'));
login.js file in route folder:
const express = require('express');
const router = express.Router();
const passport = require('passport');
const passportref = require('./../controllers/passport');
const loginController = require('./../controllers/loginController');
router.post('/putemailregistration',loginController.putEmailregistration);
router.get('/login', passportref.authenticate,loginController.verifyLogin);
module.exports = router;
Passport.js file:
const passport = require('passport');
const JWTStrategy = require("passport-jwt").Strategy;
const ExtractJwt = require('passport-jwt').ExtractJwt;
const models = require('./../models');
const opts = {
jwtFromRequest: ExtractJwt.fromAuthHeaderAsBearerToken(),
secretOrKey: 'incredible',
}
passport.use(new JWTStrategy(opts,async (payload, done) => {
try {
console.log(`inside jwt strategy func`);
const user = models.Userabout.findById({
where: { email: { [Op.eq]: payload.email } },
attributes: ['id', 'email', 'password'],
});
console.log(`value of user: ${user}`);
if (typeof user !== 'undefined' && user !== null) {
return done(null, user);
}
else {
return done(null, false);
}
} catch (err) {
done(err, false);
}
}));
module.exports = {
initialize: () => passport.initialize(),
authenticate: passport.authenticate("jwt", { session: false }),
};
loginController.js file:
const { Op } = require('sequelize');
const bcrypt = require('bcryptjs');
const jwt = require('jsonwebtoken');
const models = require('./../models');
const saltRounds = 10;
module.exports.putEmailregistration = async (req, res) => {
try {
console.log(`inside put email registration`);
if (req.body.email === null || req.body.password === null) {
res.sendStatus(400).json('no data');
} else {
const emailregister = await models.Userdata.create({
email: req.body.email,
password: bcrypt.hashSync(req.body.password,
bcrypt.genSaltSync(saltRounds)),
});
const tokenid = jwt.sign({
id: emailregister.id,
email: emailregister.email,
}, process.env.JWT_SECRETKEY,
{ expiresIn: 3600 });
res.json({ success: true, token: 'bearer ' + tokenid });
}
} catch (err) {
console.log(`error at put email registration: ${err}`);
}
}
module.exports.verifyLogin = (req, res) => {
console.log(`i managed to get here`);
// console.log(`user: ${req.user}`);
// res.send(req.user.email);
}