I'm using passport-jwt and my strategy is setup like:
let jwtOptions = {}
jwtOptions.jwtFromRequest = ExtractJwt.fromAuthHeaderAsBearerToken()
jwtOptions.secretOrKey = process.env.SECRET
var strategy = new JwtStrategy(jwtOptions, function (jwt_payload, next) {
console.log('payload received', jwt_payload);
// usually this would be a database call:
var user = users[_.findIndex(users, { id: jwt_payload.id })];
if (user) {
next(null, user);
} else {
next(null, false);
}
})
passport.use(strategy)
So when I POST to a /login route, I'm able to generate a token:
var payload = { id: user.id }
var token = jwt.sign(payload, jwtOptions.secretOrKey)
res.json({ message: "ok", token: token })
But then when I try to have a route that requires a token:
app.get("/secret", passport.authenticate('jwt', { session: false }), (req, res) => {
res.json("Success! You can not see this without a token");
})
My header has Authorization: JWT [token]
it continually returns a 401. What am I doing wrong?
Your authorization header is incorrectly formatted. Per the jwt-strategy docs
fromAuthHeaderAsBearerToken()creates a new extractor that looks for the JWT in the authorization header with the scheme 'bearer'
So your header should be Authorization: Bearer [token]
if you are sending token in header and using your own scheme (in your case you are using "JWT" ) you can use fromAuthHeaderWithScheme(auth_scheme) method.
you can find more detail in passport-jwt docs :
https://www.npmjs.com/package/passport-jwt
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With