我正在尝试在我的node.js应用程序中使用passport.js来验证使用MongoDB的用户.我从来没有成功过.
在帖子中,我发送"email":"email@gmail.com","密码":"测试"
var passport = require('passport')
, LocalStrategy = require('passport-local').Strategy;
app.post('/login',
passport.authenticate('local', { successRedirect: '/',
failureRedirect: '/fail' })
);
passport.use(new LocalStrategy({
emailField: 'email',
passwordField: 'passw',
},
function (emailField, passwordField, done) {
process.nextTick(function () {
db.collection(users, function (error, collection) {
if (!error) {
collection.findOne({
'email': emailField,
'password': passwordField
}, function (err, user) {
if (err) {
return done(err);
}
if (!user) {
console.log('this email does not exist');
return done(null, false);
}
return done(null, user);
});
} else {
console.log(5, …Run Code Online (Sandbox Code Playgroud) 我遇到了一个问题,当我尝试使用护照登录时,页面不会重定向.授权返回true(正确的用户名,密码).
我很确定它位于我的validPassword功能中,但我不确定.
登录路线
app.get('/login', function (req, res) {
res.render('login', {});
});
Run Code Online (Sandbox Code Playgroud)
登录发布
app.post('/login',
passport.authenticate('local', { successRedirect: '/',
failureRedirect: '/login' }));
Run Code Online (Sandbox Code Playgroud)
用户原型
User.prototype.validPassword = function(username, unhashedPassword) {
async.waterfall([
function (callback) {
User.find({ "username" : username }, function (err, data) {
if(err) return handleError(err);
callback(null, data);
});
},
function (data, callback) {
var isGood = passwordHash.verify(unhashedPassword, data[0].password);
callback(null, isGood);
}
], function (err, result) {
return result;
});
};
Run Code Online (Sandbox Code Playgroud)
地方战略
passport.use(new LocalStrategy(
function(username, password, done) {
var unhashedPassword …Run Code Online (Sandbox Code Playgroud) 我面临一个非常奇怪的情况,与mongoDb的初始连接大约需要15秒。我当前的设置如下:
重新启动nodemon后,初始登录POST大约需要15秒
POST /api/v1/signin 200 14707ms - 56b
Run Code Online (Sandbox Code Playgroud)
在不重新启动服务器的情况下将其他POST发送到同一路由相对较快:
POST /api/v1/signin 200 76ms - 56b
Run Code Online (Sandbox Code Playgroud)
之所以困扰我,是因为该项目仍在开发中,nodemon往往会大量重启,而测试却很痛苦。
我正在使用以下与数据库和身份验证有关的节点模块:
这是我连接到mongo的方式:
var mongoUrl = "mongodb://devmachine.local:27017/project";
mongoose.connect(mongoUrl, {auto_reconnect: true});
Run Code Online (Sandbox Code Playgroud)
任何帮助将不胜感激。
谢谢
我正在使用Express(v4.11.2)和Passport,以支持多个提供商(本地,Facebook,Twitter和谷歌)访问我正在构建的Web应用程序.作为后端,我正在使用mysql.现在我有两个本地策略:local-signup和local-signin.我遇到的问题是req.session.passport和req.user总是空的,事实上,从不调用serializeUser和deserializeUser.
这是快递和护照的设置:
var bodyParser = require('body-parser');
var session = require('express-session');
var MemoryStore = session.MemoryStore;
var _ = require('underscore');
var passport = require('passport');
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended: true}));
app.use(session({
key: 'KEY',
secret: 'SECRET331156%^!fafsdaasd',
store: new MemoryStore({reapInterval: 60000 * 10}),
saveUninitialized: true,
resave: false
}));
app.use(passport.initialize());
app.use(passport.session());
require('./config/passport')(passport); // pass passport for configuration
Run Code Online (Sandbox Code Playgroud)
这是带有身份验证策略的护照文件:
module.exports = function (passport) {
passport.serializeUser(function (user, done) {
logger.info('SERIALIZE USER');
done(null, user.id);
});
passport.deserializeUser(function (id, done) {
logger.info('DESEIRALIZE USER!');
mysqllib.getConnection(function (err, connection) {
if (err) {
done(err);
}
var …Run Code Online (Sandbox Code Playgroud) 从文档:
Passport 在 req(也称为 logOut())上公开了一个 logout() 函数,可以从任何需要终止登录会话的路由处理程序调用该函数。调用 logout() 将删除 req.user 属性并清除登录会话(如果有)。
Run Code Online (Sandbox Code Playgroud)app.get('/logout', function(req, res){ req.logout(); res.redirect('/'); });
通过阅读本文并测试自己,似乎并没有logout从客户端中删除 cookie。据我了解,当客户端发出请求时,它会发送它的 cookie,Passport 将其反序列化并转换为req.user.
假设logout不删除cookie,并且Passport 使用cookie 来确定用户是否登录,该logout函数实际上是如何将用户注销的?
javascript authentication node.js passport-local passport.js
我首先看过持有护照,mongodb和express的持续会话,但它没有帮助或有意义.
我正试图通过我的网站获得持久登录.我的序列化过程无效.
// Passport needs to be able to serialize and deserialize users to support persistent login sessions
passport.serializeUser(function(user, done) {
console.log('serializing user:',user.username);
//return the unique id for the user
return done(null, user._id);
});
//Desieralize user will call with the unique id provided by serializeuser
passport.deserializeUser(function(id, done) {
User.findById(id, function(err, user) {
console.log('deserializing user:',user.username);
return done(err, user);
});
});
Run Code Online (Sandbox Code Playgroud)
整个护照文件可以在github上找到.
我认为问题是我立即反序列化,或者至少是console.logs显示的内容.
或者它可能与我的会话:
app.use(session({
secret: 'keyboard cat',
cookie : {
maxAge: 3600000 // see below
}
})); …Run Code Online (Sandbox Code Playgroud) 我创建了一个使用护照和本地身份验证策略的Koa应用程序.我想使用模块koa-generic-session,这样我就可以将会话数据存储在Redis中.
我如何一起使用这两个?
我发现这个repo做了这个,但它似乎并没有真正使用会话,我不确定它是否正确:https://github.com/dozoisch/koa-react-full-example
我真的passport很难在我的 Node.js 应用程序中工作。我尝试重新排序我的需求,app.js但我仍然无法让它工作。这是我得到的错误:
Not Found
404
Error: Not Found
at /home/salma/Desktop/my-project/app.js:56:13
at Layer.handle [as handle_request] (/home/salma/Desktop/my-project/node_modules/express/lib/router/layer.js:95:5)
at trim_prefix (/home/salma/Desktop/my-project/node_modules/express/lib/router/index.js:312:13)
at /home/salma/Desktop/my-project/node_modules/express/lib/router/index.js:280:7
at Function.process_params (/home/salma/Desktop/my-project/node_modules/express/lib/router/index.js:330:12)
at next (/home/salma/Desktop/my-project/node_modules/express/lib/router/index.js:271:10)
at /home/salma/Desktop/my-project/node_modules/express/lib/router/index.js:618:15
at next (/home/salma/Desktop/my-project/node_modules/express/lib/router/index.js:256:14)
at next (/home/salma/Desktop/my-project/node_modules/express/lib/router/route.js:121:14)
at complete (/home/salma/Desktop/my-project/node_modules/passport/lib/middleware/authenticate.js:250:13)
at /home/salma/Desktop/my-project/node_modules/passport/lib/middleware/authenticate.js:257:15
at pass (/home/salma/Desktop/my-project/node_modules/passport/lib/authenticator.js:421:14)
at Authenticator.transformAuthInfo (/home/salma/Desktop/my-project/node_modules/passport/lib/authenticator.js:443:5)
at /home/salma/Desktop/my-project/node_modules/passport/lib/middleware/authenticate.js:254:22
at /home/salma/Desktop/my-project/node_modules/passport/lib/http/request.js:60:7
at pass (/home/salma/Desktop/my-project/node_modules/passport/lib/authenticator.js:267:43)
at serialized (/home/salma/Desktop/my-project/node_modules/passport/lib/authenticator.js:276:7)
at /home/salma/Desktop/my-project/config/passport.js:9:9
at pass (/home/salma/Desktop/my-project/node_modules/passport/lib/authenticator.js:284:9)
at Authenticator.serializeUser (/home/salma/Desktop/my-project/node_modules/passport/lib/authenticator.js:289:5)
at IncomingMessage.req.login.req.logIn (/home/salma/Desktop/my-project/node_modules/passport/lib/http/request.js:50:29)
at Strategy.strategy.success (/home/salma/Desktop/my-project/node_modules/passport/lib/middleware/authenticate.js:235:13)
Run Code Online (Sandbox Code Playgroud)
这是我的代码:
app.js:
var express = require('express'); …Run Code Online (Sandbox Code Playgroud) 我正在此入门项目的基础上构建,并尝试添加带有Passport-local-mongoose 的用户登录名。
根据我尝试使用策略的两种方式中的哪一种,我会收到此错误:
[1] passport.use(User.createStrategy());
[1] ^
[1] TypeError: User.createStrategy is not a function
Run Code Online (Sandbox Code Playgroud)
或者这个错误:
[1] passport.use(new LocalStrategy(User.authenticate()));
[1] ^
[1] TypeError: User.authenticate is not a function
Run Code Online (Sandbox Code Playgroud)
我试过在谷歌上搜索了很多解决方案,但似乎找不到任何相关的东西。
编辑:据我所知userSchema.plugin(passportLocalMongoose);,./models/user.ts应该将功能添加到模型中。配置 Passport/Passport-Local和Simplified Passport/Passport-Local Configuration显示了如何设置它,但它似乎对我不起作用。
相关依赖版本:
"dependencies": {
"cookie-parser": "^1.4.3",
"express": "^4.14.0",
"express-session": "^1.15.3",
"mongoose": "^4.7.2",
"passport": "^0.3.2",
"passport-local": "^1.0.0",
"passport-local-mongoose": "^4.0.0",
"session-file-store": "^1.0.0",
"typescript": "~2.2.0",
},
"devDependencies": {
"ts-node": "~2.0.0",
},
Run Code Online (Sandbox Code Playgroud)
./models/user.ts
import * as mongoose from 'mongoose';
const passportLocalMongoose …Run Code Online (Sandbox Code Playgroud) 我按照passport.js的文档使用passport-local:http : //www.passportjs.org/docs/authorize/
当我将用户发送给/login他们时,他们已通过身份验证,但在该文档中没有任何地方可以找到如何授权我的用户。
我试过这个,但这给了我一个bad request:
router.get('/somepage', passport.authenticate('local'), function(req, res, next) {
});
Run Code Online (Sandbox Code Playgroud)
我正在寻找一次保护我所有页面的方法。我正在使用 Express 4.16 并使用不同的路由文件来拆分我的路由。
山姆
node.js ×10
passport-local ×10
passport.js ×10
javascript ×3
express ×2
mongodb ×2
mongoose ×2
koa ×1
session ×1
typescript ×1