Simple use of session in Nodejs and methods of authentication through session
- 2020-12-18 01:44:00
- OfStack
session does not need much introduction, so that one http can correspond to one end user.
The essence of session is implemented using cookie.
The principle is as follows: http brings the server to set cookie in advance, and the server takes cookie which identifies the user, and then goes to a fixed location (database, file) to retrieve the corresponding user identity. Assign the identity to request for this request, and the user's identity is known in the processing of the program. (In PHP,ASP, or any other server language, it does this automatically for you.)
Implement cookie
Each user needs to have an cookie that identifies the user. The following rules can be used
Value of MD5 + password MD5 + random code MD5. (For example only, this may not be a good solution)
Server-side code snippet:
res.setHeader("Set-Cookie", ["sid="+newUser.toCookie()+";path=/;domain="+config.domain+";expires="+new Date("2030") ]);
cookie
sid=275fccab7935736ff68c95c3ddbfaaee|275fccab7935736ff68c95c3ddbfaaee|275fccab7935736ff68c95c3ddbfaaee
Use cookie to get the user identity and set session
All requests for non-static resources are directed here for processing. Get cookie, break up cookie and find eligible users in the database. Finally, next is used 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();
}
}
Here's how nodejs implements authentication through session
nodejs express session Authentication
1) Introduce modules
var session = require('express-session');
var cookieParser = require('cookie-parser');
2) Use cookie and session
app.use(cookieParser());
app.use(session({
resave: true, // don't save session if unmodified
saveUninitialized: false, // don't create session until something stored
secret: 'love'
}));
3) Apply authentication when the request is made
app.use(function(req,res,next){
if (!req.session.user) {
if(req.url=="/login"){
next();// If the requested address is login, go ahead 1 A request
}
else
{
res.redirect('/login');
}
} else if (req.session.user) {
next();
}
});
4) Login 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');
});