I'm building my first API / Authentication Server. I'm using Node, Express, Postgres, Sequelize, JWT's. I can signup/signin and recieve a token using my User_Controller, but when I try to access an authenticated route I either get an unauthorized response or nothing. I'm pretty sure the issue is in my passport.js file where I setup my local strategy and JWT strategy. I've tinkered with it all day but I can't figure it out. here is my passport.js file, where I think the issue occurs
const passport = require('passport');
const config = require('../config');
const user = require('../models').user;
const JwtStrategy = require('passport-jwt').Strategy;
const ExtractJwt = require('passport-jwt').ExtractJwt;
const LocalStrategy = require('passport-local');
const localLogin = new LocalStrategy({
usernameField: 'email',
passwordField: 'pass'
},
(username, password, done) => {
log.debug("Login process:", username);
return User.findOne({where:{email,password}})
.then((result)=> {
return done(null, result);
})
.catch((err) => {
log.error("/login: " + err);
return done(null, false, {message:'Wrong username or password'});
});
});
//setup options for jwt strategy
const jwtOptions = {
jwtFromRequest: ExtractJwt.fromHeader('authorization'),
secretOrKey: config.secret
};
const jwtLogin = new JwtStrategy(jwtOptions,function(payload, done){
//check payload to see if the userID is in the database
//if it is call 'done' with that user
//otherwise call done without the user object
user.findOne({where:{id:payload.sub}})
.then(user => {
if(!user) return done(null, false, {message:'sorry incorrect credentials'})
done(null, user)
})
.catch(err => done(null, false, {message:'sorry please login'}))
});
//tell passport to use this strategy
passport.use(jwtLogin);
passport.use(localLogin);
and this is my protected route:
app.get('/',requireAuth,(req,res) => {res.status(200).send({hello:'world'});});
app.post('/signup', userController.signup);
app.post('/signin', userController.signin);
Thanks for any help, its my first time doing this, I've read documentation for days and multiple walkthrough tutorials but this stuff is tricky.
via Arash
No comments:
Post a Comment