401未经授权在邮递员中使用PassportJWT

时间:2019-08-17 18:11:49

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

我有一个配置了Passport JWT的节点js后端,我认为我可以成功登录并注册并返回令牌,但是当我尝试在Postman中使用承载令牌获取req.user时,我失败了,未授权401

我尝试用payload.sub,payload.payload.doc_id和payload.doc_id替换payload.id,但我认为这些都不起作用

UserSchema / UserModel.js:

const mongoose = require("mongoose");
const bcryptjs = require('bcryptjs')

const UserSchema = mongoose.Schema({
  username: String,
  password: String
}, {collection: "Users"});

UserSchema.pre('save', async function() {
  if(this.isModified('password') || this.isNew) {
    const salt = await bcryptjs.genSalt();
    const hash = await bcryptjs.hash(this.password, salt);
    this.password = hash;
  }
})

module.exports = UserSchema;

=========================================

Userdao.server.js:

const mongoose = require("mongoose");
const UserSchema = require('../FoodHubbackendmodel/Users.schema.server');
const UserModel = mongoose.model('UserModel', UserSchema);


createUser = (userObject) => {
  return UserModel.create({
    username: userObject.username,
    password: userObject.password
  })
}

findOneUser = (user) => {
  return UserModel.findOne({username: user.email})
}

findOneById = (id) => {
  return UserModel.findOne({_id: id});
}

module.exports = {
  createUser,
  findOneUser,
  findOneById
}

========================================

Server.js

require('./data')();
let express = require("express");
let bodyParser = require('body-parser');
let app = express();
const Userdao = require('../backend/FoodHubbackenddao/User.dao.server');
let bcryptjs = require('bcryptjs')
let jsonwebtoken = require('jsonwebtoken')
let passport = require('passport')

app.use(function(req, res, next) {
  res.header("Access-Control-Allow-Origin", "*");
  res.header("Access-Control-Allow-Headers",
    "Origin, X-Requested-With, Content-Type, Accept");
  res.header("Access-Control-Allow-Methods",
    "GET, POST, PUT, DELETE, OPTIONS");
  next();
})

let cookieParser = require('cookie-parser');

// Start All the Routes

app.use(express.static(__dirname + 'public'));
app.use(bodyParser.urlencoded({ extended: true }));
app.use(cookieParser());
app.use(bodyParser.json());
app.use(passport.initialize());

var JwtStrategy = require('passport-jwt').Strategy;
var ExtractJwt = require('passport-jwt').ExtractJwt;
var opts = {};
opts.jwtFromRequest = ExtractJwt.fromAuthHeaderAsBearerToken();
opts.secretOrKey = 'AHSDEUIYEIUER';
passport.use(
  new JwtStrategy(opts, (jwt_payload, done)  => {
      Userdao.findOneById(jwt_payload.data._id).then((err, user) => {
          if(err) {
            return done(err, false);
          }
          if(user) {
            return done(null, user);
          } else {
            return done(null, false);
          }
        }
      )}
  ))

app.post('/api/register', (req, res) => {
  Userdao.createUser({username: req.body.email, password: req.body.password})
    .then(user => {
    return res.json({success: true, message: 'user created successfully'});
  }).catch(err => {
    res.send(err);
  })
})

app.post('/api/login', (req, res) => {
  const user = Userdao.findOneUser({email: req.body.email}).then(user => {
    if(!user) {
      return res.status(400).json({err: "invalid username or password"})
    } else {
      bcryptjs.compare(req.body.password, user.password).then(matched => {
        if(!matched) {
          return res.status(401).json({err: "invalid credentials"});
        } else {
          const token = jsonwebtoken.sign({id: user._id}, 'ahgd123', {expiresIn: '1d'});
          res.send({success: true, token : token})
        }
      })
    }
  }).catch(err => {
    return res.status(500).json(err);
  })
})

app.post('/api/test', passport.authenticate('jwt', {session: false}), (req, res) => {
  return res.json(req.user);
})

app.listen(3002)

Package.json

"private": true,
  "dependencies": {
    "@angular/animations": "~7.1.0",
    "@angular/common": "~7.1.0",
    "@angular/compiler": "~7.1.0",
    "@angular/core": "~7.1.0",
    "@angular/forms": "~7.1.0",
    "@angular/platform-browser": "~7.1.0",
    "@angular/platform-browser-dynamic": "~7.1.0",
    "@angular/router": "~7.1.0",
    "bcryptjs": "^2.4.3",
    "core-js": "^2.5.4",
    "firebase": "^6.0.2",
    "jsonwebtoken": "^8.5.1",
    "passport": "^0.4.0",
    "passport-jwt": "^4.0.0",
    "passport-local": "^1.0.0",
    "rxjs": "~6.3.3",
    "tslib": "^1.9.0",
    "zone.js": "~0.8.26"

我希望登录后进入POST / api / test时会获取用户json数据,但我却得到401未经授权。我已经将标题设置为带有承载令牌的授权

0 个答案:

没有答案