Session is not much to introduce, so that an HTTP can correspond to an end user.
The nature of the session is implemented using cookies.
The principle is probably: HTTP brings the server to set the cookie in advance, the server gets the cookie that identifies the user, and then retrieves the corresponding user identity from the fixed location (database, file). Assign the identity to this request, in the process of processing will know the identity of the user. (It is automatically implemented in php,asp or other service-side languages)
Implementing cookies
You need to set up a cookie that identifies the user for each user. You can use the following rules
Registered mailbox MD5 value + Password MD5 value + Random code MD5 value. (Just for example, this may not be a good plan)
Service-Side code fragment:
Cookies
Use cookies to get user identities, set session
All requests for non-static resources are directed to this process. Gets the cookie, splits the cookie, and finds the eligible user in the database. Finally, use next to jump to the next request logic.
The next request logic simply uses Req.session.user to get the user object.
Session:function (req, res, next) {
req.session = {};
if (req.cookies && req.cookies.sid) {
var a = Req.cookies.sid.split ("|");
var hexmail = a[0];
var hexpwd = a[1];
var hexrandom = a[2];
Usermodel.hexfind (Hexmail, hexpwd, Hexrandom, function (status) {
//console.log ("Hexfind", status);
if (Status.code = = "0") {
//req.cookiesselecter = Cookiesselecter;
Req.session.user = Status.result;
}
Next ();
});
else{
Next ();
}
Now let's talk about Nodejs authentication through session
Nodejs Express Session Authentication
1) Introduction of modules
var session = require (' express-session ');
var cookieparser = require (' Cookie-parser ');
2 application of cookies and session
App.use (Cookieparser ());
App.use ({
resave:true,//don ' t save session if unmodified
saveuninitialized:false,//don ' t create Sess Ion until something stored
secret: ' Love '
});
3 when requesting, apply authentication
App.use (function (req,res,next) {
if (!req.session.user) {
if (req.url== "/login") {
next ();// If the requested address is a login, proceed with the next request
}
else
{
res.redirect ('/login ');
}
else if ( Req.session.user) {
next ();
}
});
4) Landing Design
App.get ('/login ', function (req,res) {res.render ("login");}); App.post ('/login ', function (req,res) {if (req.body.username== "Love" && req.body.password== "Love") {var user = {' username ': ' Love '}
;
Req.session.user = user;
Res.redirect ('/admin/app/list ');
else {res.redirect ('/login ');}});
App.get ('/logout ', function (req,res) {req.session.user = null; Res.redirect ('/login ');});