E
E
E-em2017-07-09 22:40:00
JavaScript
E-em, 2017-07-09 22:40:00

Can't understand nodejs express jwt passport authorization error?

Hello everyone, I’m slowly sorting out the node and with how to do normal jwt + passport authorization, there is
one error left: if I enter the data correctly and make a request for /login, it issues a token, then when I try to make a get request to an address that requires a token, I get 401 Unauthorized although I add Authorization header with
Passport token

const JwtStrategy = require('passport-jwt').Strategy;
const ExtractJwt = require('passport-jwt').ExtractJwt;
const User = require('../models/user');
const config = require('./index');

module.exports = function(passport) {
    const jwtOptions = {
        jwtFromRequest: ExtractJwt.fromAuthHeader(),
        secretOrKey: config.secret
    };
    passport.use(new JwtStrategy(jwtOptions, function(payload, done) { 
        User.findById(payload.id, (error, user) => {
            if (error) {
                return done(error);
            }

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

        });
    }));
}

Answer the question

In order to leave comments, you need to log in

1 answer(s)
E
emp1re, 2017-07-09
@E-em

According to the first mistake, everything is simple, I did not look for everything, but here
It is necessary to exit the function i.e. do a return, the error says that you are trying to make a response after it has already been made. Look for places where you do 2 different responses on if.
On the second question, I don’t see serialize / deserialize the essence of the passport, that it gets the user from the database into the req body, look if you have req.user if not, then you need to deserialize and then through serialize both the session and the user will be checked.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question