护照-jwt总是返回未经授权的401

时间:2019-04-08 11:49:21

标签: javascript node.js passport.js passport-jwt

我正在尝试使用passport-jwt身份验证策略对nodejs api进行身份验证,但是它总是抛出401未经授权的错误。我尝试了各种实现,但是passport.authenticate函数似乎不起作用。

使用以下护照版本:
“ passport”:“ ^ 0.4.0”,
“ passport-jwt”:“ ^ 4.0.0”,

请在下面查看我的代码:

尝试了以下选项:

jwtFromRequest: ExtractJwt.fromAuthHeaderAsBearerToken()  
jwtFromRequest: ExtractJwt.fromHeader('authorization')  
jwtFromRequest: ExtractJwt.fromAuthHeaderWithScheme('Bearer')  
jwtFromRequest: ExtractJwt.fromAuthHeaderWithScheme('jwt')  

但不起作用。

还尝试了passport-jwt 401 Unauthorized和其他链接以供参考。

app.js文件:

const express = require('express');
const bodyParser = require('body-parser');
const passport = require('passport');
const cors = require('cors');

const app = express();
const login = require('./routes/login');

app.use(cors());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());
// app.use(passport.initialize());

app.use('/', login);

app.listen(8000, () => console.log('Server running on http://localhost:8000/'));

route文件夹中的login.js文件:

const express = require('express');
const router = express.Router();
const passport = require('passport');
const passportref = require('./../controllers/passport');
const loginController = require('./../controllers/loginController');

router.post('/putemailregistration',loginController.putEmailregistration);
router.get('/login', passportref.authenticate,loginController.verifyLogin);

module.exports = router;

Passport.js文件:

const passport = require('passport');
const JWTStrategy = require("passport-jwt").Strategy;
const  ExtractJwt = require('passport-jwt').ExtractJwt;
const models = require('./../models');

const opts = {
  jwtFromRequest: ExtractJwt.fromAuthHeaderAsBearerToken(),
  secretOrKey: 'incredible',
}
passport.use(new JWTStrategy(opts,async (payload, done) => {
 try {
     console.log(`inside jwt strategy func`);
     const user = models.Userabout.findById({
         where: { email: { [Op.eq]: payload.email } },
         attributes: ['id', 'email', 'password'],
     });
     console.log(`value of user: ${user}`);
     if (typeof user !== 'undefined' && user !== null) {
        return done(null, user);
     }
     else {
        return done(null, false);
     }
 } catch (err) {
     done(err, false);
 }
 }));


module.exports = {
    initialize: () => passport.initialize(),
    authenticate: passport.authenticate("jwt", { session: false }),
};

loginController.js文件:

const { Op } = require('sequelize');
const bcrypt = require('bcryptjs');
const jwt = require('jsonwebtoken');
const models = require('./../models');
const saltRounds = 10;

module.exports.putEmailregistration = async (req, res) => {
  try {
      console.log(`inside put email registration`);

      if (req.body.email === null || req.body.password === null) {
          res.sendStatus(400).json('no data');
      } else {
         const emailregister = await models.Userdata.create({
             email: req.body.email,
             password: bcrypt.hashSync(req.body.password, 
              bcrypt.genSaltSync(saltRounds)),
         });
        const tokenid = jwt.sign({
            id: emailregister.id,
            email: emailregister.email,
        }, process.env.JWT_SECRETKEY,
        { expiresIn: 3600 });
        res.json({ success: true, token: 'bearer ' + tokenid });
     }
   } catch (err) {
    console.log(`error at put email registration: ${err}`);
   }
}


module.exports.verifyLogin = (req, res) => {
  console.log(`i managed to get here`);

  // console.log(`user: ${req.user}`);
 // res.send(req.user.email);
}

4 个答案:

答案 0 :(得分:1)

要解决此问题,您可以在中间件中对其进行管理

function authorized(request, response, next) {
    passport.authenticate('jwt', { session: false, }, async (error, token) => {
        if (error || !token) {
            response.status(401).json({ message: 'Unauthorized Message' });
        } 
        try {
            console.log('token',token)
            const user = await User.findOne(
                {_id: token._id}
            );
            request.user = user;
        } catch (error) {
            next(error);
        }
        next();
    })(request, response, next);   
}

router.get(
  '/',
  authorized,
  trimRequest.all,
  user.getItems
)

答案 1 :(得分:1)

就我而言,我使用的是环境变量中的 expiresIn 值。环境变量值将是 String 类型,如果我们将字符串值传递给 expiresIn,它将以毫秒为单位。因此,值 3600 被转换为 3 秒,当我将登录响应中的令牌复制到 auth 标头时,它已过期。

https://www.npmjs.com/package/jsonwebtoken#usage

答案 2 :(得分:0)

Use passport.use('jwt',new JWTStrategy({opts},verify_callback(){}) in passport.js

答案 3 :(得分:0)

经过大量调试,我终于解决了该问题。希望这可以帮助某人

  1. 由于错误,我指出了passport.js文件中的错误模型。它是Userdata而不是Userabout。
  2. 在loginController.js文件中,我进行了如下更改:
    const有效负载= {id:emailregister.id}
    const token = jwt.sign(有效载荷,jwtOptions.secretOrKey);
  3. 使用以下选项效果很好。
    jwtOptions.jwtFromRequest = ExtractJwt.fromAuthHeaderWithScheme('Bearer');