Passport-jwt未经授权 [英] Passport-jwt Unauthorized

查看:208
本文介绍了Passport-jwt未经授权的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是Node js的新手.我正在使用护照jwt进行身份验证.当我尝试进行身份验证时,它始终显示未经授权".

I'm New to node js. I'm using passport jwt for authentication. When i tried to authenticate, its always showing "unauthorized".

我的 passport.js 文件

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

module.exports = function(passport){
  let opts = {};
  opts.jwtFromRequest = ExtractJwt.fromAuthHeaderAsBearerToken();
  opts.secretOrKey = config.secret;
  passport.use(new JwtStrategy(opts, (jwt_payload, done) => {

    User.getUserById(jwt_payload._doc._id, (err, user) => {
      if(err){
        return done(err, false);
      }

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

用户模型user.js

user model user.js

module.exports.getUserById = function(id, callback){
  User.findById(id, callback);
}

路线

router.get('/profile', passport.authenticate('jwt', {session:false}), (req, res, next) => {
  res.json({user: req.user});
});

当我在Google上搜索时,许多人建议在passport.js中更改此行

When I google it many suggested to change this line in passport.js

User.getUserById(jwt_payload._doc._id, (err, user) => {

我尝试过

User.getUserById(jwt_payload._id, (err, user) => {
User.findById(jwt_payload._id, (err, user) => {

现在我仍然遇到同样的错误.

still now i'm getting this same error.

推荐答案

我发现了问题所在, 在新的password-jwt更新中,我们必须使用

I found out the issue, In new passport-jwt updates, we have to use

opts.jwtFromRequest = ExtractJwt.fromAuthHeaderWithScheme('jwt');

这篇关于Passport-jwt未经授权的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆