简体   繁体   中英

Passport JWT unauthorized after logging in

My app with passport-JWT don't want to work properly as after login I can see only

Unauthorized

the login algorythm itself works good as it checks user credentials etc. but the part where passport should use JWTStrategy doesn't work at all. I went across multiple questions and answers here, in stackoverflow hoping to find an answer but I can't see anything helpful. The whole concept I made was built using this tutorial but changing small details

fromAuthHeaderAsBearerToken => fromAuthHeaderWithScheme('jwt')

but still it doesn't work. after logging in I can't see any new cookies set on my browser or something. Where the problem could be? The main thing is that I can't even reach and print console.trace(jwtPayload); on my Passport.js:

 const passport = require('passport'); const LocalStrategy = require('passport-local').Strategy; const passportJWT = require("passport-jwt"); const ExtractJwt = passportJWT.ExtractJwt; const JWTStrategy = passportJWT.Strategy; const models = require('../models/index'); passport.use(new LocalStrategy({ usernameField: 'name', passwordField: 'password' }, (user, password, cb) => { return models.User.findOne({ attributes: ['id', 'user_password', 'user_name'], where: {user_name: user} }).then(User => { if (!User) return cb(null, false, {message: 'No matching results for such a user.'}); return User.validPassword(password).then(result => { if (result !== true) return cb(null, false, {message: 'Invalid password for selected user'}); return cb(null, User.get({plain: true}), { message: 'Logged In Successfully' }); }) }).catch(err => { return cb(err); }); })); let options = {}; options.jwtFromRequest = ExtractJwt.fromAuthHeaderWithScheme('jwt'); options.secretOrKey = 'token'; options.expiresIn = (86400 * 30); console.log(options); passport.use(new JWTStrategy(options, function(jwtPayload, cb){ console.trace(jwtPayload); return models.User.findOneById(jwtPayload.id).then(User => { console.log(User); if (User) { return cb(null, User.get({plain: true})); } else { return cb(null, false); } }).catch(err => { return cb(err); }); })); 

and also my router to handle authentication

router.post('/doAuth', function (req, res, next) {

passport.authenticate('local', {session: false}, (err, user, info) => {
    if (err || !user) {
        return res.json({
            message: info ? info.message : 'Login failed',
            status: 'error'
        });
    }

    req.login(user, {session: false}, (err) => {
        if (err) {
            res.json({
                message: err,
                status: 'error'
            });
        }

        const token = jwt.sign(user, 'token', {expiresIn: 86400 * 30});
        return res.json({
            message: 'Logged In Successfully!',
            redirect: '/dashboard',
            token: 'jwt ' + token,
            success: true,
            user: {
                id: user.id,
                name: user.user_name
            }
        });
    });
})
(req, res);

});

so after logging in I'm being redirected to /dashboard as it should be but there I can only see Unauthorized. Also in my app.js I'm using authenticate.

const passport = require('passport');
require(Paths.Helpers + 'Passport');

app.use('/dashboard', passport.authenticate('jwt', {session: false}), userRouter);

I see you are using the fromAuthHeaderWithScheme to check for the token. According to the readme that

creates a new extractor that looks for the JWT in the authorization header, expecting the scheme to match auth_scheme.

That means that when you get the token when logging in with /login , you need to supply it to the /dashboard in the Authorization Header of the request. Does your request include the jwt-token in the Header?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM