NodeJs:错误401(未经授权)我正在使用passport-jwt

Posted

技术标签:

【中文标题】NodeJs:错误401(未经授权)我正在使用passport-jwt【英文标题】:NodeJs :Error 401(Unauthorized) i m using passport-jwt 【发布时间】:2020-01-28 22:11:11 【问题描述】:

我正在使用nodejs mongodb和passport-jwt中间件passport.authenticate登录进行身份验证应用程序工作,我得到了令牌,但是当我在登录后尝试访问用户配置文件时,我在邮递员控制台中得到错误:401(未授权)。

这是我的应用程序代码..

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.fromAuthHeaderWithScheme('jwt');
    opts.secretOrKey = config.secret;
    passport.use(new JwtStrategy(opts, (jwt_payload, done) => 
        User.getUserById(jwt_payload.id, (err, user) => 
            if(err)
                return done(err, false);
            
            if(user)
                return done(null, user);
            else
                return done(null, false);
            
        );
    )
     );
  

users.js

const express = require("express");
const router = express.Router();
const passport = require("passport");
const jwt = require("jsonwebtoken");
const config = require("../config/database");
const User = require("../models/user");

//Register
router.post("/register", (req, res, next) => 
  //res.send('REGISTER');
  let newUser = new User(
    name: req.body.name,
    email: req.body.email,
    username: req.body.username,
    password: req.body.password
  );
  User.addUser(newUser, (err, user) => 
    if (err) 
      res.json( success: false, msg: "Failed to register user" );
     else 
      res.json( success: true, msg: "User registered" );
    
  );
);

//Authenticate
router.post("/authenticate", (req, res, next) => 
  //res.send('AUTHENTICATE');
  const username = req.body.username;
  const password = req.body.password;
  User.getUserByUsername(username, (err, user) => 
    if (err) throw err;
    if (!user) 
      return res.json( success: false, msg: "User not found!" );
    

    User.comparePassword(password, user.password, (err, isMatch) => 
      if (err) throw err;
      if (isMatch) 
        const token = jwt.sign(user.toJSON(), config.secret, 
          expiresIn: 3600 // 1week  604800
        );
        res.json(
          success: true,
          token: "JWT " + token,
          user: 
            id: user._id,
            name: user.name,
            username: user.username,
            email: user.email
          
        );
       else 
        return res.json( success: false, msg: "Worng password" );
      
    );
  );
);
//Profile
router.get("/profile", passport.authenticate('jwt', session: false), (req, res, next) => 
 // res.send("PROFILE");
 res.json(user: req.user._id);
 
);


module.exports = router;

user.js

const mongoose = require('mongoose');
const bcrypt = require('bcryptjs');
const config = require('../config/database');

//User Schema
const UserSchema = mongoose.Schema(
    name:
        type: String
    ,
    email:
        type: String,
        required: true
    ,
    username:
        type: String,
        required: true
    ,
    password:
        type: String,
        required: true
    
);

const User = module.exports = mongoose.model('User', UserSchema);

//Getting UserById
module.exports.getUserById = function(id, callback)
    User.findById(id, callback);
    console.log("got user by id");

//Gettng UserByUserName
module.exports.getUserByUsername = function(username, callback)
    const query = username: username
    User.findOne(query, callback);


//AddUser  
 module.exports.addUser = function(newUser, callback)
    bcrypt.genSalt(10,(err, salt) =>
        bcrypt.hash(newUser.password, salt,(err, hash) =>
            if(err) throw err;
            newUser.password = hash;
            newUser.save(callback);
            console.log("new user has been added");
        );
    );
 

//Login or AUTHENCATION 
module.exports.comparePassword = function(candidatePassword, hash, callback)
  bcrypt.compare(candidatePassword, hash, (err, isMatch) => 
      if(err) throw err;
      callback(null, isMatch);
      console.log("compare pwd complete");
  );


任何帮助都非常感谢..

【问题讨论】:

【参考方案1】:

/authenticate中只返回token

token: "JWT " + token, to

token: token,

登录后的请求需要设置header:

Authorization:Bearer token

【讨论】:

我正好遇到了这个问题,这与我使用的代码相同。请提供更多关于在哪里设置Authorization: Bearer token的信息我在前端有以下内容:getProfile() let headers = new HttpHeaders(); this.loadToken(); headers.append('Authorization', this.authToken); headers.append('Content-Type', 'application/json'); return this.http .get('http://localhost:3000/users/profile', headers ) .pipe(map((res) => res));

以上是关于NodeJs:错误401(未经授权)我正在使用passport-jwt的主要内容,如果未能解决你的问题,请参考以下文章

使用 Axios 和 Firebase 时出现 401 未经授权的错误

Heroku 上的 forge.tutorial.viewhubmodels.nodejs 教程 401(未经授权)

谷歌云存储:401 未经授权的错误

Cosmos db Rest API - 错误 401 未经授权

Android推送通知未经授权的错误401

Web 服务 401:未经授权的错误