mikenicholson / passport-jwt

Passport authentication using JSON Web Tokens
MIT License
1.96k stars 213 forks source link

ExtractJwt.fromAuthHeaderAsBearerToken(), ExtractJwt.fromAuthHeader() #127

Closed Funnybanny closed 7 years ago

Funnybanny commented 7 years ago

ExtractJwt.fromAuthHeaderAsBearerToken() doesnt exist and ExtractJwt.fromAuthHeader() doesnt work, instead i used ExtractJwt.fromHeader("authorization") to get my token from the authorization header. Please remove it from documentation it took me some time to figure this out.

Dr-MHQ commented 7 years ago

I have tried ExtractJwt.fromAuthHeaderAsBearerToken() but still does not work :S what could be the issue ??

Funnybanny commented 7 years ago

the problem is ExtractJwt.fromAuthHeaderAsBearerToken() doesnt exist so if your Authorization token has Bearer before it i suggest to use ExtractJwt.fromHeader("authorization"), then from the payload which is a string cut off the bearer part

Dr-MHQ commented 7 years ago

already done with and even done ExtractJwt.fromAuthHeaderWithScheme('jwt') none works this is killing me :'(

Funnybanny commented 7 years ago

ExtractJwt.fromHeader("authorization") should work. Actually my header was Authorization and at first i used ExtractJwt.fromHeader("Authorization") and that didnt work, also try to write out the payload or simply the token

Dr-MHQ commented 7 years ago

maybe I'm loosing my mind in here so this is the code I use right not `var options = {}

options.jwtFromRequest = ExtractJwt.fromHeader('authorization'); //ExtractJwt.fromAuthHeaderAsBearerToken(); options.secretOrKey = '7x0jhxt"9(thpX6'; `

they way I'm testing it via Postman is: at the Header: Authorization => jwt xxxxx <= the token

am I doing it the wrong way ?

Funnybanny commented 7 years ago

options are correct, but what is this Authorization => jwt xxxxx <= the token. I use jwt-simple to encode my token try that because passport jwt will try to decode it

Dr-MHQ commented 7 years ago

this is the way I pass the token to server at the header section of Postman I add the key "Authorization" and the value is "jwt xxxx"

is that where I screw up ?

Funnybanny commented 7 years ago

well yeah jwt xxxx is not a jwt token. read up on jwt, but the basics are it has a payload and signiture, payload is the ifo you want to put in and signiture is your secret

Dr-MHQ commented 7 years ago

how shall I call it then ? I'm getting started with Node JS so I'm so sorry if my question is too basic

Funnybanny commented 7 years ago

well read up on jwt tokens, and i use jwt-simple to make my tokens

Dr-MHQ commented 7 years ago

so "jwt eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpZCI6IjU5YTA5ZDM0ODYwYTRiMjM0MDEwMTM4MCIsImVtYWlsIjoiYWFAYWEuY29tIiwiaWF0IjoxNTAzODE5MjkwfQ.SnIeTVn-mjA5CukAdzywkTmnHchVa7EdMcvqy9SJjGw" is not the token ?

Funnybanny commented 7 years ago

oh okay i thought you simply used xxxx XD. sorry yes thats a token, then make sure the secret in passport jwt is the same as in token. also try to remove jwt from the header and only use the token itself

Dr-MHQ commented 7 years ago

I have tested my token at jwt.io and passed the secret and it got verified ... I have also removed "jwt" from the header authorization value ... still no lock :'(

Funnybanny commented 7 years ago

well then im out of ideas sorry. Dont lose your mind over this i have been only working with node.js for 1,5 month and currently stuck with passport-ldapauth its either not as easy as it seems or its a piece of **** software

Dr-MHQ commented 7 years ago

thank you so much... maybe if you take a look at the complete file code you can spot the issue

`const express = require('express'); const mongoose = require('mongoose'); const passport = require('passport'); const LocalStrategy = require('passport-local').Strategy; const JwtStrategy = require('passport-jwt').Strategy; const ExtractJwt = require('passport-jwt').ExtractJwt; const bodyParser = require('body-parser'); const User = require('./models/user'); const routes = require('./routes') const users = require('./routes/users');

const app = express(); const PORT = 3000;

app.use(bodyParser.json()); app.use(bodyParser.urlencoded({ extended: false }));

// connect to database mongoose.Promise = global.Promise; var db = 'localhost/react-native-jwt' mongoose.connect(db); mongoose.connection.on('error', function () { console.info('Error: Could not connect to MongoDB. Did you forget to run mongod?') }).once('open', (msg)=> { console.log('connected to DB',msg); });

// JWT configuration var options = {}

options.jwtFromRequest = ExtractJwt.fromHeader('authorization'); //ExtractJwt.fromAuthHeaderAsBearerToken(); options.secretOrKey = '7x0jhxt"9(thpX6';

app.use(passport.initialize());

// Configure Passport to use local strategy for initial authentication. passport.use('local', new LocalStrategy(User.authenticate()));

// Configure Passport to use JWT strategy to look up Users. passport.use('jwt', new JwtStrategy(options, function(jwt_payload, done) { console.log('jwt payload is: ',jwt_payload); User.findOne({ _id: jwt_payload.id }, function(err, user) {

if (err) { return done(err, false); } if (user) { done(null, user); } else { done(null, false); } }) }))

app.use('/', routes);

app.use('/users', users);

app.listen(PORT, (err) => { if (err) { console.error(err); } else { console.log(Server Listening to ${PORT}) } });`

Funnybanny commented 7 years ago

well maybe try to initialize the passport after you set the strategy

Dr-MHQ commented 7 years ago

still no luck :'(

Funnybanny commented 7 years ago

also on your routes you are not using passport.authenticate(), thats how you implement it to the route app.use('/users', passport.authenticate("jwt"), users)

Dr-MHQ commented 7 years ago

the way I authenticate is: `router.get('/protected', function (req, res, next) { console.log(req.headers);

passport.authenticate('jwt', function (err, user, info) { if (err) { console.error(err); return next(err); } if (!user) { return res.status(401).json({ error: 'Invalid credentials.' ,msg:err,i:info,usr:user}); } if (user) { return res .status(200) .json({ secret: '123' }); } })(req, res, next); });`

Funnybanny commented 7 years ago

passport is a middleware so you cant just put it in a function

Dr-MHQ commented 7 years ago

IT WORKED 👍 I was using old secret at one file and another in the server file ... so I fixed it and removed the "jwt" from the token and it finally WORKED I guess I'm getting too old for this **** ;)

thank you so much

Funnybanny commented 7 years ago

good job :)

Dr-MHQ commented 7 years ago

thank you so much for your help you're a God send

mikenicholson commented 7 years ago

Sounds like this is fixed. Thanks @Funnybanny.

Funnybanny commented 7 years ago

Its not fixed its still in the documentation even though they doesnt exist

ashinzekene commented 6 years ago

Not fixed!!!!!!!!!!!!!!!!!!!!!!!!!!

rmar72 commented 6 years ago

These 2 ways worked for me: ExtractJwt.fromAuthHeaderWithScheme('bearer') or with ('jwt');

Headers: Authorization: bearer + token or jwt + token

JohnnyHandy commented 4 years ago

These 2 ways worked for me: ExtractJwt.fromAuthHeaderWithScheme('bearer') or with ('jwt');

Headers: Authorization: bearer + token or jwt + token

How do you set the header with the token after the login?

supu4aqua commented 3 years ago

I'm using fromAuthHeaderWithSchema('jwt') but still getting 'Unauthorized'. Can someone please help?

signToken = user => { return JWT.sign({ iss: 'Thinkific', sub: user.id, iat: new Date().getTime(), //Current Time exp: new Date().setDate(new Date().getDate() + 1) //Current Time + 1 day ahead }, 'JWT_SECRET'); }

--- passport.js file --- onst passport = require('passport'); const JwtStrategy = require('passport-jwt').Strategy; const { ExtractJwt } = require('passport-jwt'); const { JWT_SECRET } = require('./configuration'); const user = require('./models/user');

//Passport will get the toekn from JWT_SECRET and decode it passport.use(new JwtStrategy({ jwtFromRequest: ExtractJwt.fromAuthHeaderWithScheme('jwt'), secretOrKey: JWT_SECRET }, async (payload, done) => { try { //find the users specified in token const user = await User.findById(payload.sub); //If user doesn't exist, handle it if (!user) { return done(null, false); } //Else, return the user done(null, user); } catch (error) { done(error, false); } }));

abdalla-ayman commented 3 years ago

i used fromHeader it worked jwtFromRequest: ExtractJwt.fromHeader("authorization") // authorization = header name`