简体   繁体   English

未经授权的护照。 它甚至都不是console.log。

[英]passport jwt unauthorized. It is not even console.log anything.

I am building a login registration. 我正在建立登录注册。 I have used passport before and was able to have it working. 我以前曾使用过护照,并且能够使用它。 It seems like npm has changed the documentation. 看来npm已更改了文档。 I cannot even console.log in the function I pass passport in. I have been working and researching this issue since last night. 我什至无法在我通过护照的功能中使用console.log。自昨晚以来,我一直在研究此问题。

Currently I am able to register a user, and authenticate a user which means my register and authenticate route is working. 目前,我能够注册用户并认证用户,这意味着我的注册和认证路由正在运行。 This is verified through Postman. 这已通过邮递员进行了验证。 When I use the profile route though it is unauthorized. 当我使用配置文件路由时,尽管它是未经授权的。 I will put what I am putting through postman below after I describe the file structure and past the code for each file. 在描述文件结构并通过每个文件的代码之后,我将在下面通过邮递员介绍一下。

If you notice in the passport file, I have a console.log. 如果您在护照文件中注意到,我有一个console.log。 This does not even log while my console.log in the app.js is logging in the terminal. 当我在app.js中的console.log登录到终端时,这甚至都不会记录。 So this is all that shows in my terminal 这就是我终端中显示的所有内容

Server started on port 3000 yay i am connected to databasemongodb://localhost:27017/authapp 服务器在端口3000上启动,是的,我已连接到数据库mongodb:// localhost:27017 / authapp

Could someone please help? 有人可以帮忙吗?

Here is my file structure. 这是我的文件结构。

application
config
-database.js
-passport.js
models
-user.js
routes
-users.js
app.js
package.json

passport.js 护照

   module.exports = function(passport){
    let opts = {}; 
    opts.jwtFromRequest = ExtractJwt.fromAuthHeaderWithScheme('jwt')  
    opts.secretOrKey = config.secret; 
    passport.use(new JwtStrategy(opts, (jwt_payload,done)=>{
        console.log(jwt_payload);  
        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);
            }
        });
    }));
}

database.js database.js

module.exports = {
    database:'mongodb://localhost:27017/authapp', 
    secret:'NintamaRantaro'
}

models/user.js 型号/user.js

const mongoose = require('mongoose');
//bcrpypt for encrpyption
const bcrypt = require('bcryptjs');
//to connect to database 
const config = require('../config/database');


//Create the Schema
const UserSchema = mongoose.Schema({
    name: {
        type: String
    },
    email: {
        type: String,
        require: true,

    },
    username: {
        type: String,
        require: true
    },
    password: {
        type: String,
        require: true
    }
});

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


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

module.exports.getUserByUsername = function(username, callback){
    const query = {username:username} 
    User.findOne(query, callback); 
}



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")
    });
  });
}

module.exports.comparePassword = function(candidatePassword, hash, callback){
    bcrypt.compare(candidatePassword, hash, function(err, isMatch){
        if(err) throw err;
        callback(null, isMatch);
        console.log("compare pass complete")
    });
}

routes/users.js 路线/users.js

const express = require('express');
const router = express.Router();
const passport = require('passport');
const jwt = require('jsonwebtoken');
const config = require('../config/database')
//Now that I created the model I will bring it in here.
const User = require('../models/user');
const bodyParser = require('body-parser')

//Registration 
router.post('/register', (req,res,next) =>{
    //res.send('registration');
    let newUser = new User({
        name: req.body.name,
        email: req.body.email,
        username: req.body.username,
        password: req.body.password  //I will run this password through bcrypt.hash which will has before db.
    });
    console.log("new instance of the User class has been created")
    User.addUser(newUser, function(err, user){ //I will create this addUser function inside the models user.js
        if(err){
            console.log(err);
            res.json({success:false, msg:'Registration Failed!'})
        }else{
            res.json({success:true, msg:'User is Registered!'})
        }
    });
});
//This will be my authentication route
router.post('/authenticate', (req,res,next)=>{
    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:600000
                });
                res.json({
                    sucess:true,
                    token:'JWT ' + token,
                    user:{
                        id: user._id,
                        name: user.name,
                        username: user.username,
                        email: user.email
                    }
                });
            }else{
                return res.json({success:false, msg:'wrong pass'});
            }
        });
     });
});
// It failed at the line.
// const token = jwt.sign(user, config.secret, {
// Which I assume is mongoosejs object, which contains many methods and is not "serializable". 

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

});



module.exports = router;

app.js app.js

const express = require('express');
//path is part of the cores module
const path = require('path');
const bodyParser = require('body-parser');
const cors = require('cors');
const passport = require('passport');
const mongoose = require('mongoose');
//database is in database.js this connects to  database:'mongodb://localhost:27817/authapp'
const config = require('./config/database')

mongoose.connect(config.database); mongoose.connect(config.database);

mongoose.connect(config.database);  

mongoose.connection.on('connected',function(){console.log('yay i am connected to database'+config.database)});


mongoose.connection.on('error',function(error){console.log('You have an error'+error)});


const app = express();


const users = require('./routes/users');

const port = 3000;

app.use(cors());



app.use(express.static(path.join(__dirname, 'public')))


app.get('/', function(req,res){res.send('Sending Response')})


app.use(bodyParser.json());


app.use(passport.initialize());
app.use(passport.session());

require('./config/passport')(passport);

app.use('/users', users)


app.listen(port, function(){console.log('Server started on port '+port)})

Postman after http://localhost:3000/users/register method:Post Body: http:// localhost:3000 / users / register方法之后的邮递员:邮递正文:

{
    "name":"hello",
    "email":"hello@world.com",
    "username":"helloworld",
    "password":"123456"
}

200 OK { "success": true, "msg": "User is Registered!" 200 OK {“成功”:true,“ msg”:“用户已注册!” } }

After http://localhost:3000/users/authenticate method:Post body: http:// localhost:3000 / users / authenticate方法之后:帖子正文:

{
    "username":"helloworld",
    "password":"123456"
}

200 OK 200 OK

{
    "sucess": true,
    "token": "JWTeyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJfaWQiOiI1YTk2YzA1ZmZjNDQ5YjBkZTI0ZTA3YTIiLCJuYW1lIjoiaGVsbG8iLCJlbWFpbCI6ImhlbGxvQHdvcmxkLmNvbSIsInVzZXJuYW1lIjoiaGVsbG93b3JsZCIsInBhc3N3b3JkIjoiJDJhJDEwJGl1eFE2V1IvaXJqRkxTZVV4MkhSVE80SlhzeEhrUklzbEhGeTVGL1ZQbGdSMVBEU2wwUkRlIiwiX192IjowLCJpYXQiOjE1MTk4MjkxMTksImV4cCI6MTUyMDQyOTExOX0.05uAxA9sQMzVHjc2kXoR86fpDzu1TQmsyFbGN_AcFRo",
    "user": {
        "id": "5a96c05ffc449b0de24e07a2",
        "name": "hello",
        "username": "helloworld",
        "email": "hello@world.com"
    }
}

After http://localhost:3000/users/profile http:// localhost:3000 / users / profile之后

Headers: 标头:

Key: Authorization,
Value: JWTeyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJfaWQiOiI1YTk2YzA1ZmZjNDQ5YjBkZTI0ZTA3YTIiLCJuYW1lIjoiaGVsbG8iLCJlbWFpbCI6ImhlbGxvQHdvcmxkLmNvbSIsInVzZXJuYW1lIjoiaGVsbG93b3JsZCIsInBhc3N3b3JkIjoiJDJhJDEwJGl1eFE2V1IvaXJqRkxTZVV4MkhSVE80SlhzeEhrUklzbEhGeTVGL1ZQbGdSMVBEU2wwUkRlIiwiX192IjowLCJpYXQiOjE1MTk4MjkxMTksImV4cCI6MTUyMDQyOTExOX0.05uAxA9sQMzVHjc2kXoR86fpDzu1TQmsyFbGN_AcFRo

Unauthorized 401 Unauthorized 未经授权401未经授权

Oh my god. 哦,我的上帝。 So I fixed it. 所以我修好了。 I restarted my computer. 我重新启动了计算机。 Restarted the servers. 重新启动服务器。 Then changed user.toJSON() to {data:user}. 然后将user.toJSON()更改为{data:user}。 Finally it started printing to the console and found out the payload was coming in through an object called data. 最终,它开始打印到控制台,并发现有效负载正通过称为数据的对象进入。 Because of this I put jwt_payload.data._id instead of what I had above. 因此,我放置了jwt_payload.data._id而不是上面的内容。 I think the npm documentation has changed with updates. 我认为npm文档已随着更新而改变。 I have another Mean app using passport and I used jwt_payload._doc._id which worked before. 我有另一个使用护照的Mean应用程序,我使用过的jwt_payload._doc._id。 Also I don't think I had to put {data:user}. 另外,我认为不必放{data:user}。 I think before I just had user there. 我认为在我在那里有用户之前。 Im surprised the registration and authentication worked with user.toJSON() but didn't work with going to the profile page. 我很惊讶使用user.toJSON()进行注册和身份验证,但无法转到个人资料页面。 I really was about to give up but thankfully I tried again and again. 我真的要放弃了,但幸运的是我一次又一次地尝试。

All files look good. 所有文件看起来都不错。 I was facing the same issue and the following is the solution that I arrived at: 我遇到了同样的问题,以下是我得出的解决方案:

    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);
                }
            });
        })
         );
      }

You can check passport-jwt-npm doc .. 您可以检查护照-jwt-npm文件..

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM