我正在建立一个登录注册。我以前用过护照,现在可以用了。似乎npm已经更改了文档。我甚至不能安慰他。登录我传入passport的函数。从昨晚开始,我一直在研究这个问题。
目前,我能够注册一个用户,并对用户进行身份验证,这意味着我的注册和身份验证路由正在工作。这是通过邮递员核实的。当我使用配置文件路由时,尽管它是未经授权的。在我描述了文件结构并通过了每个文件的代码之后,我将把我正在通过的postman放在下面。
如果你在passport文件中注意到,我有一个控制台。日志这甚至不会在我的控制台运行时记录。登录应用程序。js正在登录终端。这就是我终端上显示的所有内容
服务器启动端口3000耶我连接到databasemongodb://localhost:27017/authapp
有人能帮忙吗?
这是我的文件结构。
application
config
-database.js
-passport.js
models
-user.js
routes
-users.js
app.js
package.json
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);
}
});
}));
}
module.exports = {
database:'mongodb://localhost:27017/authapp',
secret:'NintamaRantaro'
}
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")
});
}
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;
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.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)})
邮递员http://localhost:3000/users/register方法:帖子正文:
{
"name":"hello",
"email":"hello@world.com",
"username":"helloworld",
"password":"123456"
}
200确定{“success”:true,“msg”:“用户已注册!”}
之后http://localhost:3000/users/authenticate方法:帖子正文:
{
"username":"helloworld",
"password":"123456"
}
200行
{
"sucess": true,
"token": "JWTeyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJfaWQiOiI1YTk2YzA1ZmZjNDQ5YjBkZTI0ZTA3YTIiLCJuYW1lIjoiaGVsbG8iLCJlbWFpbCI6ImhlbGxvQHdvcmxkLmNvbSIsInVzZXJuYW1lIjoiaGVsbG93b3JsZCIsInBhc3N3b3JkIjoiJDJhJDEwJGl1eFE2V1IvaXJqRkxTZVV4MkhSVE80SlhzeEhrUklzbEhGeTVGL1ZQbGdSMVBEU2wwUkRlIiwiX192IjowLCJpYXQiOjE1MTk4MjkxMTksImV4cCI6MTUyMDQyOTExOX0.05uAxA9sQMzVHjc2kXoR86fpDzu1TQmsyFbGN_AcFRo",
"user": {
"id": "5a96c05ffc449b0de24e07a2",
"name": "hello",
"username": "helloworld",
"email": "hello@world.com"
}
}
之后http://localhost:3000/users/profile
标题:
Key: Authorization,
Value: JWTeyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJfaWQiOiI1YTk2YzA1ZmZjNDQ5YjBkZTI0ZTA3YTIiLCJuYW1lIjoiaGVsbG8iLCJlbWFpbCI6ImhlbGxvQHdvcmxkLmNvbSIsInVzZXJuYW1lIjoiaGVsbG93b3JsZCIsInBhc3N3b3JkIjoiJDJhJDEwJGl1eFE2V1IvaXJqRkxTZVV4MkhSVE80SlhzeEhrUklzbEhGeTVGL1ZQbGdSMVBEU2wwUkRlIiwiX192IjowLCJpYXQiOjE1MTk4MjkxMTksImV4cCI6MTUyMDQyOTExOX0.05uAxA9sQMzVHjc2kXoR86fpDzu1TQmsyFbGN_AcFRo
未经授权401未经授权
哦我的天。所以我修好了。我重启了电脑。重启服务器。然后将user.toJSON()更改为{data: user}。最后,它开始打印到控制台,发现有效载荷是通过一个叫做data的对象进来的。正因为如此,我把jwt_payload.data._id而不是上面的。我认为npm留档随着更新而改变。我有另一个平均应用程序使用护照,我用jwt_payload_doc_id以前的工作。另外,我不认为我必须把{data: user}。我想在我刚刚有用户之前。我很惊讶注册和身份验证可以使用user.toJSON(),但不能使用到个人资料页面。我真的要放弃了,但谢天谢地,我一次又一次地尝试。
所有文件看起来都不错。我也面临同样的问题,以下是我得出的解决方案:
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);
}
});
})
);
}
你可以检查护照-jwt-npm doc...