NodeJs 中的 Passport 总是返回 UnAuthorized

Passport in NodeJs always returning UnAuthorized

我一直在尝试在 nodejs 中构建一个后端应用程序,其中我有两个模式:用户和配置文件。我正在尝试使用护照对其进行身份验证,但代码似乎有问题。当我第一次执行它时它起作用了,但之后我做了一些改动,看起来我搞砸了,现在我无法找出我的代码有什么问题。现在,在邮递员中执行登录路由后,我收到了一个令牌,但是当我使用此令牌根据令牌中的有效负载获取当前用户的配置文件时,即使在 header(Authorization) 中添加了令牌之后,我也是未经授权。 以下是代码文件:

app.js

const express = require('express');
const bodyParser = require('body-parser');
const mongoose = require('./db/mongo');
const passport = require('passport')
const config = require('./config/config')
const setContentTypeJSON = require('./middleware/set-content-type-json');

const usersRouter = require('./routes/auth-routes');

const app = express();

app.use(setContentTypeJSON);
app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());

//Passport Middleware
app.use(passport.initialize())
require('./config/passport')(passport)


app.use(usersRouter);


const PORT = process.env.PORT || config.port;
mongoose.connect(config.mongoURL, { useNewUrlParser: true })
    .then(() => {
        console.log("Connection established!")
        app.listen(PORT);
    })
    .catch(() => {
        console.log("Connection failed!")
    })

passport.js

const JwtStrategy = require('passport-jwt').Strategy;
const ExtractJwt = require('passport-jwt').ExtractJwt;
const mongoose = require('mongoose');
const User = mongoose.model('users');
const keys = require('../config/config');

const opts = {};
opts.jwtFromRequest = ExtractJwt.fromAuthHeaderAsBearerToken();
opts.secretOrKey = keys.secretOrKey;

module.exports = passport => {
  passport.use(
    new JwtStrategy(opts, (jwt_payload, done) => {
      User.findById(jwt_payload.id)
        .then(user => {
          if (user) {
            return done(null, user);
          }
          return done(null, false);
        })
        .catch(err => console.log(err));
    })
  );
};

auth-routes.js

const express = require('express');
const router = express.Router();
const passport = require('passport')
const jwt = require('jsonwebtoken')
const authController = require('../controllers/auth')

router.post("/signup", authController.userSignup);
router.post('/login', authController.userLogin);
router.get('/current', authController.current);

module.exports = router;

auth.js

const bcrypt = require('bcrypt');
const jwt = require('jsonwebtoken');
const passport = require('passport');
const config = require('../config/config');
const User = require('../models/user');

exports.userLogin = (req, res, next) => {
    const email = req.body.email;
    const password = req.body.password;

    User.findOne({ email })
        .then(user => {
            if (!user) {
                return res.status(404).json({
                    email: 'User not found'
                })
            }

            bcrypt.compare(password, user.password)
                .then(isMatch => {
                    if (isMatch) { //user login successful
                        const payload = {email: user.email, userId: user._id};
                        jwt.sign(payload,
                            config.secretOrKey,
                            {expiresIn: 3600},
                            (err,token)=>{
                                if(err){
                                    res.status(404).json({
                                        error: err
                                    })
                                }
                                res.json({
                                    success: true,
                                    email: payload.email,
                                    id: payload.userId,
                                    token: 'Bearer '+token,

                                })                               
                            })
                    } else {
                        return res.status(400).json({
                            password: 'Password Incorrect'
                        });
                    }
                })
        });
}

exports.current = passport.authenticate('jwt',
{session: false}),(req,res)=>{
    res.json(req.user)
}

如果您想参考我用来创建模式的两个模型文件:

User.js

const mongoose = require('mongoose')
const uniqueValidator = require('mongoose-unique-validator')


const userSchema = mongoose.Schema({
  email: {type: String, required: true, unique: true},
  password: {type: String,required: true}  ,
  resetToken: String,
  resetTokenExpiration: Date
});

userSchema.plugin(uniqueValidator);

module.exports = mongoose.model("users",userSchema);

Profile.js

const mongoose = require('mongoose')
const Schema = mongoose.Schema;

const profileSchema = mongoose.Schema({
    user:{
        type: Schema.Types.ObjectId,
        ref: 'users'
    },
    fullname: {
        type: String,
        required: true
    },
    college:{
        type:String,
        required: true
    },
    department: {
        type: String,
        required: true
    },
    achievements:{
        type: [String],
    }
});

module.exports = mongoose.model("profile",profileSchema);

如有帮助将不胜感激!

出现了一个小错误。在 auth.js 文件中,我替换了

exports.current = passport.authenticate('jwt',{session: false}),(req,res)=>{
...
}

exports.current = (req,res)=>{
...
}

并且在 auth-routes.js 文件中,我编辑了

router.get('/current',passport.authenticate('jwt',{session: false}),authController.current);

这是错误,也许我需要再次修改我的 es6 基础知识。成功了。