I have Express as backend and am trying to add authentication using Passport.js. I want to authenticate by password only - and a unique password located in /config/main named key:
I can generate JWT by sending a POST request via /authenticate, But I cannot access the app using that JWT and I am getting ERROR 401 with Unauthorized written in Postman. My files :
passport.js
var JwtStrategy = require('passport-jwt').Strategy;
var ExtractJwt = require('passport-jwt').ExtractJwt;
var LocalStrategy = require('passport-local');
var config = require('./main');
var pass = config.key;
// Setup work and export for the JWT passport strategy
module.exports = function(passport) {
var opts = {};
opts.jwtFromRequest = ExtractJwt.fromAuthHeader();
opts.secretOrKey = config.secret;
// opts.issuer = "accounts.examplesoft.com";
// opts.audience = "yoursite.net";
passport.use(new JwtStrategy(opts, function(jwt_payload, done) {
if (jwt_payload.key === pass) {
return done(null, password);
} else {
return done(null, false);
// or you could create a new account
}
}));
};
app.js
// Initialize passport for use
app.use(passport.initialize());
// Bring in defined Passport Strategy
require('./config/passport')(passport);
var mainConfig = require('./config/main');
var key = mainConfig.key;
var pass = mainConfig.password;
// Authenticate the user and get a JSON Web Token to include in the header of future requests.
router.post('/authenticate', function(req, res) {
var token = jwt.sign({
key:'pass'
}, mainConfig.secret, { expiresIn: '24h' });
res.json({ success: true, token: 'JWT ' + token });
// Enable CORS from client-side
app.use(function(req, res, next) {
res.header("Access-Control-Allow-Origin", "*");
res.header('Access-Control-Allow-Methods', 'PUT, GET, POST, DELETE, OPTIONS');
res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept, Authorization, Access-Control-Allow-Credentials");
res.header("Access-Control-Allow-Credentials", "true");
next();
});
router.get('/home', passport.authenticate('jwt', { session: false }), function(req, res) {
});
// Set url for API group routes
app.use('/react', router);
What am I doing wrong? Please let me know so I could improve my code and go further with my website. I am new to authentication feature, so please explain what I did wrong.