node.js passport.session() 中间件有什么作用?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/22052258/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
What does passport.session() middleware do?
提问by Georges Krinker
I am building an authentication system using Passport.js using Easy Node Authentication: Setup and Local tutorial.
我正在使用 Passport.js 使用Easy Node Authentication: Setup and Local tutorial构建身份验证系统。
I am confused about what passport.session()does.
我对做什么感到困惑passport.session()。
After playing around with the different middleware I came to understand that express.session()is what sends a session ID over cookies to the client, but I'm confused about what passport.session()does and why it is required in addition to express.session().
在尝试了不同的中间件后,我开始明白这express.session()是通过 cookie 向客户端发送会话 ID 的原因,但我对passport.session()除了express.session().
Here is how I set up my application:
这是我设置应用程序的方法:
// Server.js configures the application and sets up the webserver
// Server.js 配置应用程序并设置网络服务器
//importing our modules
var express = require('express');
var app = express();
var port = process.env.PORT || 8080;
var mongoose = require('mongoose');
var passport = require('passport');
var flash = require('connect-flash');
var configDB = require('./config/database.js');
//Configuration of Databse and App
mongoose.connect(configDB.url); //connect to our database
require('./config/passport')(passport); //pass passport for configuration
app.configure(function() {
//set up our express application
app.use(express.logger('dev')); //log every request to the console
app.use(express.cookieParser()); //read cookies (needed for auth)
app.use(express.bodyParser()); //get info from html forms
app.set('view engine', 'ejs'); //set up ejs for templating
//configuration for passport
app.use(express.session({ secret: 'olhosvermelhoseasenhaclassica', maxAge:null })); //session secret
app.use(passport.initialize());
app.use(passport.session()); //persistent login session
app.use(flash()); //use connect-flash for flash messages stored in session
});
//Set up routes
require('./app/routes.js')(app, passport);
//launch
app.listen(port);
console.log("Server listening on port" + port);
回答by lindsaymacvean
passport.session()acts as a middleware to alter the req object and change the 'user' value that is currently the session id (from the client cookie) into the true deserialized user object.
passport.session()充当中间件来更改 req 对象并将当前会话 ID(来自客户端 cookie)的“用户”值更改为真正的反序列化用户对象。
Whilst the other answers make some good points I thought that some more specific detail could be provided.
虽然其他答案提出了一些很好的观点,但我认为可以提供一些更具体的细节。
app.use(passport.session());
is equivalent to
相当于
app.use(passport.authenticate('session'));
Where 'session' refers to the following strategy that is bundled with passportJS.
其中“会话”是指与passportJS 捆绑的以下策略。
https://github.com/jaredhanson/passport/blob/master/lib/strategies/session.js
https://github.com/jaredhanson/passport/blob/master/lib/strategies/session.js
Specifically lines 59-60:
特别是第 59-60 行:
var property = req._passport.instance._userProperty || 'user';
req[property] = user;
Where it essentially acts as a middleware and alters the value of the 'user' property in the req object to contain the deserialized identity of the user. To allow this to work correctly you must include serializeUserand deserializeUserfunctions in your custom code.
它本质上充当中间件并更改 req 对象中“用户”属性的值以包含用户的反序列化身份。要使其正常工作,您必须在自定义代码中包含serializeUser和deserializeUser函数。
passport.serializeUser(function (user, done) {
done(null, user.id);
});
passport.deserializeUser(function (user, done) {
//If using Mongoose with MongoDB; if other you will need JS specific to that schema.
User.findById(user.id, function (err, user) {
done(err, user);
});
});
This will find the correct user from the database and pass it as a closure variable into the callback done(err,user);so the above code in the passport.session()can replace the 'user' value in the req object and pass on to the next middleware in the pile.
这将从数据库中找到正确的用户并将其作为闭包变量传递给回调,done(err,user);因此上面的代码passport.session()可以替换 req 对象中的“用户”值并传递给堆中的下一个中间件。
回答by Josh C.
From the documentation
从文档
In a Connect or Express-based application, passport.initialize() middleware is required to initialize Passport. If your application uses persistent login sessions, passport.session() middleware must also be used.
在基于 Connect 或 Express 的应用程序中,需要passport.initialize() 中间件来初始化Passport。如果您的应用程序使用持久登录会话,则还必须使用passport.session() 中间件。
and
和
Sessions
In a typical web application, the credentials used to authenticate a user will only be transmitted during the login request. If authentication succeeds, a session will be established and maintained via a cookie set in the user's browser.
Each subsequent request will not contain credentials, but rather the unique cookie that identifies the session. In order to support login sessions, Passport will serialize and deserialize user instances to and from the session.
会话
在典型的 Web 应用程序中,用于对用户进行身份验证的凭据只会在登录请求期间传输。如果身份验证成功,将通过用户浏览器中设置的 cookie 建立和维护会话。
每个后续请求将不包含凭据,而是包含标识会话的唯一 cookie。为了支持登录会话,Passport 将在会话中序列化和反序列化用户实例。
and
和
Note that enabling session support is entirely optional, though it is recommended for most applications. If enabled, be sure to use express.session() before passport.session() to ensure that the login session is restored in the correct order.
请注意,启用会话支持完全是可选的,但建议大多数应用程序使用它。如果启用,请确保在passport.session() 之前使用express.session() 以确保以正确的顺序恢复登录会话。
回答by uniwalker
While you will be using PassportJsfor validating the user as part of your login URL, you still need some mechanism to store this user information in the session and retrieve it with every subsequent request (i.e. serialize/deserialize the user).
虽然您将PassportJs用于验证用户作为登录 URL 的一部分,但您仍然需要某种机制来将此用户信息存储在会话中并在每个后续请求中检索它(即序列化/反序列化用户)。
So in effect, you are authenticating the user with every request, even though this authentication needn't look up a database or oauth as in the login response. So passport will treat session authentication also as yet another authentication strategy.
因此,实际上,您正在对每个请求进行用户身份验证,即使此身份验证不需要像在登录响应中那样查找数据库或 oauth。因此,passport 也将会话身份验证视为另一种身份验证策略。
And to use this strategy - which is named session, just use a simple shortcut - app.use(passport.session()). Also note that this particular strategy will want you to implement serialize and deserialize functions for obvious reasons.
并且要使用这个策略——它是命名的session,只需使用一个简单的快捷方式—— app.use(passport.session())。另请注意,出于明显的原因,此特定策略将希望您实现序列化和反序列化功能。
回答by Jared Hanson
It simply authenticates the session (which is populated by express.session()). It is equivalent to:
它只是验证会话(由 填充express.session())。它相当于:
passport.authenticate('session');
as can be seen in the code here:
如此处的代码所示:
https://github.com/jaredhanson/passport/blob/42ff63c/lib/authenticator.js#L233
https://github.com/jaredhanson/passport/blob/42ff63c/lib/authenticator.js#L233

