Reputation: 381
I am using JWT to do authentication with a user in my express app. One of the routes needs to be authenticated before continuing so I am doing so like this per following the documentation and a tutorial:
router.post('/current/update', passport.authenticate('jwt', { session: false }),(res, req) => {
console.log(req.body) //undefined
}
passport.js
const JwtStrategy = require('passport-jwt').Strategy;
const ExtractJwt = require('passport-jwt').ExtractJwt;
const mongoose = require('mongoose');
const Account = mongoose.model('accounts')
const keys = require('./keys');
const opts = {};
opts.jwtFromRequest = ExtractJwt.fromAuthHeaderAsBearerToken();
opts.secretOrKey = keys.secretOrKey;
module.exports = passport => {
passport.use(
new JwtStrategy(opts, (jwt_payload, done) => {
Account.findById(jwt_payload.id)
.then(account => {
if(account){
return done(null, account)
}
return done(null, false)
}).catch(err => {
console.log(err)
return done(err)
})
})
);
};
Not knowing how to get access to the body of the request is troubling because that means I don't know how to get access to the req.params
and req.query
. I have tried numerous methods, including passing the req
along with the strategy:
new JwtStrategy(opts, (req, jwt_payload, done) => ...
So question is, if not gotten from above, is how do I get access to the req
object, other than just req.user
so that I am able to handle parameterized URLs and queries?
Upvotes: 0
Views: 759
Reputation: 4164
You need to tell the JwtStrategy to pass the req
object to your callback. You can do this via the options object you supply to the strategy. Your code will look something like this:
const opts = {};
opts.jwtFromRequest = ExtractJwt.fromAuthHeaderAsBearerToken();
opts.secretOrKey = keys.secretOrKey;
opts.passReqToCallback = true; // New option!
Then in your callback function you'll need to also accept the req
field which comes in as the first argument to the function. So your callback initialisation goes from
new JwtStrategy(opts, (jwt_payload, done)
and becomes
new JwtStrategy(opts, (req, jwt_payload, done)
You can then access the full express request object via req
. As noted in the comments, you'll also need something like body-parser
to ensure it's decoded properly.
Upvotes: 1