如何使用护照和护照-jwt正确保护我的所有路线

时间:2019-08-29 10:22:22

标签: reactjs passport.js passport-jwt

我构建了此React应用,并且正在使用本地护照来对管理员和用户进行身份验证。我已经能够遵循一些教程并验证用户身份。现在,我想实现jwt来保护某些路由,但是我似乎没有使其工作。使用邮递员,我可以注册并登录,然后获得令牌。但是,当我尝试受保护的路由时,会收到401未经授权的响应。任何帮助,将不胜感激。

我已经能够遵循一些教程并验证用户身份。现在,我想实现jwt来保护某些路由,但是我似乎没有使其工作。使用邮递员,我可以注册并登录,然后获得令牌。但是,当我尝试受保护的路由时,会收到401未经授权的响应。任何帮助,将不胜感激。

const JwtStrategy = require('passport-jwt').Strategy;
const ExtractJWT = require('passport-jwt').ExtractJwt;
const config = require('./secret');

// const salt = bcrypt.genSaltSync(10);


module.exports = (userType, passport) => {
    const opts = {
        jwtFromRequest: ExtractJWT.fromAuthHeaderWithScheme('JWT'),
        secretOrKey: config.secret,
    };

passport.use('jwt', new JwtStrategy(opts, (jwt_payload, done) => {
    try {
        User.findOne({
            where: {
                id: jwt_payload.id,
            },
        }).then(user => {
            if (user) {
                console.log('user found in db in passport');
                done(null, user);
            } else {
                console.log('user not found in db');
                done(null, false);
            }
        });
    } catch (err) {
        done(err);
    }
})
)

passport.use(
    'login',
    new LocalStrategy(
        {
            usernameField: 'username',
            passwordField: 'password',
            session: false,
        },
        (username, password, done) => {
            try {
                User.findOne({
                    where: {
                        username,
                    },
                }).then(user => {
                    if (user === null) {
                        return done(null, false, { message: 'bad username' });
                    }
                    bcrypt.compare(password, user.password).then(response => {
                        if (response !== true) {
                            console.log('passwords do not match');
                            return done(null, false, { message: 'passwords do not match' });
                        }
                        console.log('user found & authenticated');
                        return done(null, user);
                    });
                });
            } catch (err) {
                done(err);
            }
        },
    ),
);

这就是我要保护路线的方式:

 router.get('/api/clients', (req, res, next) => {
passport.authenticate('jwt', { session: false }, (err, user, info) => {
    if (err) {
        console.log(err);
    }
    if (info !== undefined) {
        console.log(info.message);
        res.status(401).send(info.message);
    } else if (user.username === req.query.username) {
        User.findOne({
            where: {
                username: req.query.username,
            },
        }).then((userInfo) => {
            if (userInfo != null) {
                console.log('user found in db');
                res.status(200).send({
                    auth: true,
                    // first_name: userInfo.first_name,
                    // last_name: userInfo.last_name,
                    email: userInfo.email,
                    username: userInfo.username,
                    password: userInfo.password,
                    message: 'user found in db',
                });
                db.Client.findAll({}).then(function (dbClient) {
                    res.json(dbClient);
                });
            } else {
                console.error('no user exists in db with that username');
                res.status(401).send('no user exists in db with that username');
            }
        });
    } else {
        console.error('jwt id and username do not match');
        res.status(403).send('username and jwt token do not match');
    }
})(req, res, next);

});

1 个答案:

答案 0 :(得分:0)

我可以通过简化受保护的路由来解决此问题,如下所示:

 app.get('/auth/api/clients', 
passport.authenticate('jwt', {
session: false
  }), (req, res) => {

console.log(req.user);
// console.log(res)
return (db.Client.findAll({}).then(function 
(dbClient) {
  if (typeof dbClient === "object") {
    res.json(dbClient);
     }
   }
   ));
  });

现在一切正常。