我正在建立登录注册。我之前使用过护照,并且能够使用护照。似乎npm已经改变了文档。我甚至无法在我通过护照的功能中使用console.log。自昨晚以来,我一直在研究这个问题。
目前,我可以注册用户,并对用户进行身份验证,这意味着我的注册和身份验证路由正在运行。这是通过Postman验证的。当我使用配置文件路由时,虽然它是未经授权的。在我描述文件结构并通过每个文件的代码之后,我将把我通过邮递员提供的内容放在下面。
如果您在护照文件中注意到,我有一个console.log。当app.js中的console.log登录终端时,这甚至都没有记录。 所以这就是我终端中的所有内容
服务器在端口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 OK { "成功":是的, " msg":"用户已注册!" }
http://localhost:3000/users/authenticate之后 方法:帖子 体:
{
"username":"helloworld",
"password":"123456"
}
200 OK
{
"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未经授权
答案 0 :(得分:0)
天哪啊。所以我修好了。我重新启动了电脑。重启服务器。然后将user.toJSON()更改为{data:user}。最后,它开始打印到控制台,发现有效负载是通过一个名为data的对象进入的。因为这个我把jwt_payload.data._id而不是我上面的东西。我认为npm文档随更新而改变。我有另一个使用护照的Mean应用程序,我之前使用过jwt_payload._doc._id。我也不认为我必须放{data:user}。我想在我之前有用户之前。我很惊讶注册和身份验证使用user.toJSON(),但无法进入配置文件页面。我真的要放弃但谢天谢地,我一次又一次地尝试。
答案 1 :(得分:0)
所有文件看起来不错。我面临着同样的问题,以下是我得出的解决方案:
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);
}
});
})
);
}
您可以查看passport-jwt-npm doc ..