问题描述
我在开发中正在使用带护照的节点/快递。我发现一篇文章说:但是令我惊讶的是,在登录之前和之后,浏览器Cookie中sessionID存储的值保持不变。那么序列化用户对象在哪里存储?我以为它最初存储在用户sessionid cookie中,但似乎不是这样,因为我仍然可以使用 req.session.passport.user
$ b访问我的用户对象$ b简短
序列化的用户对象存储在因此,您在应用程序和护照 c $ c>或 server.js 文件非常重要。如果你声明你的会话和护照配置上面 static directory configs 那么对静态内容的所有请求也将获得一个会话,这不是很好。
看到我的答案这个,我曾经提到有关静态内容访问以及如何有选择地将护照应用于某些路由,而不是默认值(您可能不需要验证所有路由),因此您可以避免不必要的会话存储查找和解除序列化通过将会话仅附加到映射到安全URL的请求,请参见下文)。
//有选择地将护照复制到安全网址
app.use(function(req,res,next){
if(req.url.match('/ xxxx / secure'))
passport.session()(req,res,next)
else
next(); / /不要求护照
});
有一个惊人的,如果您想了解PassportJS的工作流程,我强烈建议您阅读。
I am using node/express with passport in my development. I came across an article which says:
But to my surprise, the value for sessionID stores in the browser cookies remain the same before and after login. So where does the serialised user object is stored? I thought that it was stored in the user sessionid cookie initially but it seems that this is not the case as i still can access my user object with req.session.passport.user
In Short
The serialized user object is stored in req.user by PassportJS taken from req.session.passport.user (which is is populated by Express) with the help of Passport's deserializeUser method.
Express adds the id of the session object into a cookie on user's browser, which is sent back to express in a header on every request. Express then takes the id from the header and search the session store (i.e. Mongo or whatever) and find the entry and load it to req.session.
PassportJS uses the content of req.session to keep track of the authenticated user with the help of serializeUser and deserializeUser methods (for more information on workflow of serializeUser and deserializeUser see my answer in this SO question).
Express is responsible for creating the session. when does the sessions gets created? That is when Express do not detect a session cookie. So the order in which you organize your session and passport configs in your app or server.js file is very important. If you declare your session and passport configs above static directory configs then all requests for static content will also get a session, which is not good.
See my answer to this SO question, where I have mentioned about static content access as well as how to selectively apply passport to certain routes, rather than default (you might not need to authenticate all the routes - hence you could avoid unnecessary session store lookup and de-serialization by attaching session only to requests that map to secure URLS see below).
//selectively applying passport to only secure urls app.use(function(req, res, next){ if(req.url.match('/xxxx/secure')) passport.session()(req, res, next) else next(); // do not invoke passport });
There is one amazing tutorial that I highly recommend you to read up if you want to understand the workflow of PassportJS.
这篇关于护照js如何在会话中存储用户对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!