Passport authentication with JWTStrategy not working even jwt is not getting called even the console.log({ jwt_payload }); is not getting called
roshen1234 opened this issue · 2 comments
//index.js file
const express = require('express');
const server = express();
const mongoose = require('mongoose');
const cors = require('cors');
const session = require('express-session');
const passport = require('passport');
const LocalStrategy = require('passport-local').Strategy;
const crypto = require('crypto');
const jwt = require('jsonwebtoken');
const JwtStrategy = require('passport-jwt').Strategy;
const ExtractJwt = require('passport-jwt').ExtractJwt;
const { createProduct } = require('./controller/Product');
const productsRouter = require('./routes/Products');
const categoriesRouter = require('./routes/Category');
const brandsRouter = require('./routes/Brands');
const usersRouter = require('./routes/User');
const authRouter = require('./routes/Auth');
const cartRouter = require('./routes/Cart');
const ordersRouter = require('./routes/Order');
const { User } = require('./model/user');
const { isAuth, sanitizeUser } = require('./services/common');
const port=8080;
const SECRET_KEY = 'SECRET_KEY';
// JWT options
const opts = {};
opts.jwtFromRequest = ExtractJwt.fromAuthHeaderAsBearerToken();
opts.secretOrKey = SECRET_KEY; // TODO: should not be in code;
//middlewares
server.use(
session({
secret: 'keyboard cat',
resave: false, // don't save session if unmodified
saveUninitialized: false, // don't create session until something stored
})
);
server.use(passport.authenticate('session'));
server.use(
cors({
exposedHeaders: ['X-Total-Count'],
})
);
server.use(express.json()); // to parse req.body
server.use('/products', isAuth(), productsRouter.router);
// we can also use JWT token for client-only auth
server.use('/categories', isAuth(), categoriesRouter.router);
server.use('/brands', isAuth(), brandsRouter.router);
server.use('/users', isAuth(), usersRouter.router);
server.use('/auth', authRouter.router);
server.use('/cart', isAuth(), cartRouter.router);
server.use('/orders', isAuth(), ordersRouter.router);
// Passport Strategies
passport.use(
'local',
new LocalStrategy(async function (username, password, done) {
// by default passport uses username
try {
const user = await User.findOne({ email: username });
console.log(username, password, user);
if (!user) {
return done(null, false, { message: 'invalid credentials' }); // for safety
}
crypto.pbkdf2(
password,
user.salt,
310000,
32,
'sha256',
async function (err, hashedPassword) {
if (!crypto.timingSafeEqual(user.password, hashedPassword)) {
return done(null, false, { message: 'invalid credentials' });
}
const token = jwt.sign(sanitizeUser(user), SECRET_KEY);
done(null, token); // this lines sends to serializer
}
);
} catch (err) {
done(err);
}
})
);
passport.use(
'jwt',
new JwtStrategy(opts, async function (jwt_payload, done) {
console.log({ jwt_payload });
try {
const user = await User.findOne({ id: jwt_payload.sub });
if (user) {
return done(null, sanitizeUser(user)); // this calls serializer
} else {
return done(null, false);
}
} catch (err) {
return done(err, false);
}
})
);
// this creates session variable req.user on being called from callbacks
passport.serializeUser(function (user, cb) {
console.log('serialize', user);
process.nextTick(function () {
return cb(null, { id: user.id, role: user.role });
});
});
// this changes session variable req.user when called from authorized request
passport.deserializeUser(function (user, cb) {
console.log('de-serialize', user);
process.nextTick(function () {
return cb(null, user);
});
});
const mongoURI="mongodb://0.0.0.0/ecommerce"
mongoose.connect(mongoURI)
const conn=mongoose.connection
conn.once('open',()=>{
console.log('successfullly connected to database')
})
conn.once('error',(error)=>{
console.log(failed to connected to database${error.message}
)
})
server.listen(port, () => {
console.log(Ecommerce backend listening at http://localhost:${port}
)
})
//common.js file
const passport = require('passport');
exports.isAuth = (req, res, done) => {
return passport.authenticate('jwt')
};
exports.sanitizeUser = (user)=>{
return {id:user.id, role:user.role}
}
//auth routes
const express = require('express');
const { createUser, loginUser, checkUser } = require('../controller/Auth');
const passport = require('passport');
const router = express.Router();
// /auth is already added in base path
router.post('/signup', createUser)
.post('/login', passport.authenticate('local'), loginUser)
.get('/check',passport.authenticate('jwt'), checkUser);
exports.router = router;
i have spent lot of time but still not able to find the msitake
Same