passport.session () 미들웨어는 무엇을합니까?
Easy Node Authentication : Setup and Local tutorial을 사용하여 Passport.js를 사용하여 인증 시스템을 구축하고 있습니다 .
나는 무엇을하는지 혼란 스럽다 passport.session().
서로 다른 미들웨어와 놀아 후 나는 이해했다 express.session()클라이언트에 쿠키를 통해 세션 ID를 전송하는,하지만 난이 일에 대해 혼란스러워하고있어 passport.session()하며 만약에 추가로 필요한 이유 express.session().
내 애플리케이션을 설정하는 방법은 다음과 같습니다.
// 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);
passport.session() req 개체를 변경하고 현재 세션 ID (클라이언트 쿠키에서) 인 '사용자'값을 진정한 역 직렬화 된 사용자 개체로 변경하는 미들웨어 역할을합니다.
다른 답변은 좋은 점을 제시하지만 좀 더 구체적인 세부 사항을 제공 할 수 있다고 생각했습니다.
app.use(passport.session());
다음과 같다
app.use(passport.authenticate('session'));
여기서 '세션'은 passportJS와 함께 제공되는 다음 전략을 나타냅니다.
https://github.com/jaredhanson/passport/blob/master/lib/strategies/session.js
특히 59-60 행 :
var property = req._passport.instance._userProperty || 'user';
req[property] = user;
본질적으로 미들웨어 역할을하며 사용자의 역 직렬화 된 ID를 포함하도록 req 개체의 'user'속성 값을 변경합니다. 이것이 올바르게 작동하려면 사용자 정의 코드에 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);
});
});
이것은 데이터베이스에서 올바른 사용자를 찾아 콜백에 클로저 변수로 전달 done(err,user);하므로의 위 코드가 passport.session()req 객체의 'user'값을 대체하고 더미의 다음 미들웨어로 전달할 수 있습니다.
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.
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.
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.
While you will be using PassportJs for 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).
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.
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.
It simply authenticates the session (which is populated by express.session()). It is equivalent to:
passport.authenticate('session');
as can be seen in the code here:
https://github.com/jaredhanson/passport/blob/master/lib/authenticator.js#L236
참고URL : https://stackoverflow.com/questions/22052258/what-does-passport-session-middleware-do
'Programing' 카테고리의 다른 글
| Rest API 서버용 Scala 프레임 워크? (0) | 2020.08.14 |
|---|---|
| C ++ 용 Vim 구성 (0) | 2020.08.14 |
| phpexcel을 사용하여 데이터를 읽고 데이터베이스에 삽입하는 방법은 무엇입니까? (0) | 2020.08.13 |
| Powershell.exe (v 2.0) 경로 (0) | 2020.08.13 |
| 클래스 메소드를 생성하기 위해 define_method를 어떻게 사용합니까? (0) | 2020.08.13 |