我正在建立一个登录注册。我以前用过护照,现在可以用了。似乎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未经授权
所有文件看起来都不错。我也面临同样的问题,以下是我得出的解决方案:
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...
哦我的天。所以我修好了。我重启了电脑。重启服务器。然后将user.toJSON()更改为{data: user}。最后,它开始打印到控制台,发现有效载荷是通过一个叫做data的对象进来的。正因为如此,我把jwt_payload.data._id而不是上面的。我认为npm留档随着更新而改变。我有另一个平均应用程序使用护照,我用jwt_payload_doc_id以前的工作。另外,我不认为我必须把{data: user}。我想在我刚刚有用户之前。我很惊讶注册和身份验证可以使用user.toJSON(),但不能使用到个人资料页面。我真的要放弃了,但谢天谢地,我一次又一次地尝试。
我正在处理一个在平均堆栈上运行的Web应用程序(遵循TraversyMedia教程)。然而,我遇到了一个问题,这里提供的任何解决方案似乎都不适合我。每当我尝试访问我的/个人资料页面(除非您获得授权,否则该页面将受到保护)时,我都会收到返回的错误。但是,我已登录并拥有正确的访问令牌。 我已经看了护照jwt git。但是我所拥有的似乎是匹配的。我尝试过使用: 目前正在使用:ExtractJwt。fro
我已经被困在Laravel护照问题上4天了。以下是我验证登录凭据的代码库,从而验证用户登录(基于令牌) 我已经完成了护照整合的所有步骤。 我调用的API(来自邮递员): http://localhost/oauth/token/?email=admin@test.com 即 config/auth。php 但是我得到了错误: 我收到的错误 现在,由于这不起作用,我尝试了以下方法: 但这次我收到了:
问题内容: 我从Nexus存储库中检出了代码。我更改了帐户密码,并在文件中正确设置了密码。在执行时,我收到错误消息,说明它尝试从该存储库下载文件。 任何想法如何解决此错误?我在Maven 3.04中使用Windows 7 问题答案: 这里的问题是所使用的密码出现错字错误,由于密码中使用了字符/字母,因此很难识别。
我有一个Quarkus项目,它公开了一些RESTendpoint。当在开发模式下工作或从本地构建docker容器中运行时,所有工作都很好,那些用@rolesalloved和@permitall注释的endpoint都正常工作。但是当我按照以下步骤部署到AWS服务时: 提交到Gitlab 运行Gitlab cicd 将结果与配置一起发送到AWS S3 bucket 触发AWS CodePipelin
我有一个带有/api/users/register和/api/users/loginendpoint的spring boot项目,registerendpoint工作正常,允许我发布以创建新用户(带有验证等),但当我尝试使用正确的详细信息登录时,登录endpoint会给我401(未经授权)响应。 此外,我正在尝试在创建用户时为他们添加新角色,但由于我使用的是JWT,我不确定如何进行此操作,每个在线