Closed Funnybanny closed 7 years ago
I have tried ExtractJwt.fromAuthHeaderAsBearerToken() but still does not work :S what could be the issue ??
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
already done with and even done ExtractJwt.fromAuthHeaderWithScheme('jwt') none works this is killing me :'(
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
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 ?
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
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 ?
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
how shall I call it then ? I'm getting started with Node JS so I'm so sorry if my question is too basic
well read up on jwt tokens, and i use jwt-simple to make my tokens
so "jwt eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpZCI6IjU5YTA5ZDM0ODYwYTRiMjM0MDEwMTM4MCIsImVtYWlsIjoiYWFAYWEuY29tIiwiaWF0IjoxNTAzODE5MjkwfQ.SnIeTVn-mjA5CukAdzywkTmnHchVa7EdMcvqy9SJjGw" is not the token ?
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
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 :'(
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
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}
)
}
});`
well maybe try to initialize the passport after you set the strategy
still no luck :'(
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)
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); });`
passport is a middleware so you cant just put it in a function
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
good job :)
thank you so much for your help you're a God send
Sounds like this is fixed. Thanks @Funnybanny.
Its not fixed its still in the documentation even though they doesnt exist
Not fixed!!!!!!!!!!!!!!!!!!!!!!!!!!
These 2 ways worked for me: ExtractJwt.fromAuthHeaderWithScheme('bearer') or with ('jwt');
Headers: Authorization: bearer + token or jwt + token
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?
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); } }));
i used fromHeader it worked
jwtFromRequest:
ExtractJwt.fromHeader("authorization") // authorization = header name`
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.