Session Implementation principle
There are many ways to implement request authentication, and one widely accepted approach is to use the session ID generated by the server to implement the session management with the browser's cookie, which generally includes the following 4 steps:
- Server-side Generation session ID
- Server side and client store session ID
- Extract session ID from HTTP header
- Obtain requester identity information from server-side hash based on session ID
implementation of Session management using Express and Redis
var session = require (' express-session ');
var Redisstrore = require (' Connect-redis ') (session);
var config={
"Cookie": {
"MaxAge": 1800000
},
"Sessionstore": {
"Host": "192.168.0.13",
"Port": "6379",
"Pass": "123456",
"DB": 1,
"TTL": 1800,
"Logerrors": True
}
App.use (Session ({
Name: "Sid",
Secret: ' asecret123-',
Resave:true,
Rolling:true,
Saveuninitialized:false,
Cookie:config.cookie,
Store:new Redisstrore (Config.sessionstore)
}));
Implementing the Stack
Express-session calling code after instantiation (https://github.com/expressjs/session)
if (!req.sessionid) { debug (' No SID sent, generating session '); Generate (); Next (); return; }
Generate Method Invocation (https://github.com/expressjs/session)
Store.generate = function (req) { Req.sessionid = Generateid (req); Req.session = new session (req); Req.session.cookie = new Cookie (cookieoptions); if (cookieoptions.secure = = = ' Auto ') { req.session.cookie.secure = issecure (req, trustproxy); } };
Redisstrore called Store.set (SID, Session, callback) when instantiating (https://github.com/expressjs/session)
Store.set calls Redisstore. Prototype. Set (Https://github.com/tj/connect-redis), where the seat HashKey uses the prefix +sessonid, the prefix default value is ' Sess ', multiple apps are shared and the same Redis session service is not shared
Be sure to pay attention to setting prefix
RedisStore.prototype.set = function (SID, Sess, fn) { var store = this; var args = [Store.prefix + SID]; if (!FN) fn = NoOp; try { var jsess = store.serializer.stringify (Sess); } catch (er) { return fn (er); } Args.push (jsess); if (!store.disablettl) { var ttl = Getttl (store, sess); Args.push (' EX ', TTL); Debug (' SET '%s '%s ttl:%s ', sid, Jsess, TTL); } else { debug (' SET '%s '%s ', sid, Jsess); } Store.client.set (args, function (er) { if (er) return fn (er); Debug (' SET complete '); Fn.apply (null, arguments); });
Store. client. set is called (Https://github.com/NodeRedis/node_redis)
final call to native Redis. Hset Method
Using Redis management session under Nodejs Express