简体   繁体   English

登录后未经授权的Passport JWT

[英]Passport JWT unauthorized after logging in

My app with passport-JWT don't want to work properly as after login I can see only 我的护照为JWT的应用程序无法正常运行,因为登录后我只能看到

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. 登录算法本身可以很好地工作,因为它可以检查用户凭据等。但是,护照应该使用JWTStrategy的部分根本不起作用。 I went across multiple questions and answers here, in stackoverflow hoping to find an answer but I can't see anything helpful. 我在这里遇到了多个问题和答案,在stackoverflow中希望找到答案,但是我看不到任何有用的东西。 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. 登录后,我看不到浏览器上设置的任何新cookie。 Where the problem could be? 问题可能出在哪里? The main thing is that I can't even reach and print console.trace(jwtPayload); 最主要的是,我什至无法到达并打印console.trace(jwtPayload); on my Passport.js: 在我的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. 因此,登录后我应该被重定向到/dashboard ,但是在那里我只能看到Unauthorized。 Also in my app.js I'm using authenticate. 同样在我的app.js中,我正在使用身份验证。

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. 我看到您正在使用fromAuthHeaderWithScheme检查令牌。 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. 创建一个新的提取器,以在授权标头中查找JWT,期望该方案与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. 这意味着,当您使用/login时获得令牌时,您需要将其提供给请求的授权标题中的/dashboard Does your request include the jwt-token in the Header? 您的请求是否在标题中包含jwt-token?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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