express session realize Log Express + Session achieve login authentication

https://www.cnblogs.com/mingjiatang/p/7495321.html

 

Express + Session achieve login authentication

 

1. EDITORIAL

When we log on a website, without logging out, we closed the site, over time, open the site again, still will be logged. This is because, when we log on a web site, the login server will save us until we log out, or save login status expired. That server is through what our store login status of it? The answer is that Session, Session by service able to record the status of each client connections. Session on principle, and in which not much to say, this paper introduces the Express framework, how to implement user login authentication using the Session.

2. Environment Configuration

In Node environment and not integrated Express and Session libraries, hence the need for installation, first enter the establishment of a project directory, and then in the project root directory, use the following command to install four modules.
1) Express
This module will allow us to quickly build a Web development framework.
2) body-parser
This module is a module Express middleware to help us resolve the body to the data sent by the browser.
3) express-session
The module also Express middleware module to help us deal with the client's session.
4) ejs
This module is a rendering engine. Help us bind variable data back to the front page.
Installation is as follows:

npm install express --save
npm install body-parser --save npm install express-session --save npm install ejs --save

3. Log in and verify

Session state of the client can be marked on the server. Using this, we can achieve the client's login authentication. Session login authentication process substantially as follows: If the client requests a home page while logged in, the server redirects the request to the login page; client after login, the server needs to save logged record of the client, and give a duration of the activity, so that the next time the server requests the home page, you can log on to determine the status of the client, if the login status is valid, the client needs to return to the page directly, otherwise redirected to the login page.

For Session expiration time, if not set an expiration time Session, the server will default validity period based on their configuration, the long-term interaction with the server to delete the Session.

I posted the following example code, the interface is relatively simple, back-end server code comments written very clearly, and therefore no longer be explained.

The directory structure of the project are as follows:

Login page (login.html) code is as follows:

<!DOCTYPE html>
<html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> <style type="text/css"> </style> </head> <body> <form action="/login" method="POST"> 用户名: <input type="text" name="username"/> <br> 密码: <input type="password" name="pwd"/> <input type="submit" value="Submit"/> </form> </body> </html>

Home (home.html) code is as follows:

<!DOCTYPE html>
<html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> <div>用户名:<span><%= username %> </span> <a href="/logout">退出登录</a></div> </body> </html>

Server (app.js) code is as follows:

/**
 * Created by tjm on 9/7/2017.
 */

var express = require('express');
var app = express(); var session = require('express-session'); var bodyparser = require('body-parser'); // 下面三行设置渲染的引擎模板 app.set('views', __dirname); //设置模板的目录 app.set('view engine', 'html'); // 设置解析模板文件类型:这里为html文件 app.engine('html', require('ejs').__express); // 使用ejs引擎解析html文件中ejs语法 app.use(bodyparser.json()); // 使用bodyparder中间件, app.use(bodyparser.urlencoded({ extended: true })); // 使用 session 中间件 app.use(session({ secret : 'secret', // 对session id 相关的cookie 进行签名 resave : true, saveUninitialized: false, // 是否保存未初始化的会话 cookie : { maxAge : 1000 * 60 * 3, // 设置 session 的有效时间,单位毫秒 }, })); // 获取登录页面 app.get('/login', function(req, res){ res.sendFile(__dirname + '/login.html') }); // 用户登录 app.post('/login', function(req, res){ if(req.body.username == 'admin' && req.body.pwd == 'admin123'){ req.session.userName = req.body.username; // 登录成功,设置 session res.redirect('/'); } else{ res.json({ret_code : 1, ret_msg : '账号或密码错误'});// 若登录失败,重定向到登录页面 } }); // 获取主页 app.get('/', function (req, res) { if(req.session.userName){ //判断session 状态,如果有效,则返回主页,否则转到登录页面 res.render('home',{username : req.session.userName}); }else{ res.redirect('login'); } }) // 退出 app.get('/logout', function (req, res) { req.session.userName = null; // 删除session res.redirect('login'); }); app.listen(8000,function () { console.log('http://127.0.0.1:8000') })

This, session realize login verification is complete. The above example session is stored in the service memory, of course, can also be saved in a file or database, middleware can only need to configure session.

app.use(session({
    secret: 'secretkey',
    store: new MongoStore({
        db: 'sessiondb' }) }));

The above code is sucked MongoDB database to save the session, of course, some Session configuration, specific reference: https://www.npmjs.com/package/express-session

1. EDITORIAL

When we log on a website, without logging out, we closed the site, over time, open the site again, still will be logged. This is because, when we log on a web site, the login server will save us until we log out, or save login status expired. That server is through what our store login status of it? The answer is that Session, Session by service able to record the status of each client connections. Session on principle, and in which not much to say, this paper introduces the Express framework, how to implement user login authentication using the Session.

2. Environment Configuration

In Node environment and not integrated Express and Session libraries, hence the need for installation, first enter the establishment of a project directory, and then in the project root directory, use the following command to install four modules.
1) Express
This module will allow us to quickly build a Web development framework.
2) body-parser
This module is a module Express middleware to help us resolve the body to the data sent by the browser.
3) express-session
The module also Express middleware module to help us deal with the client's session.
4) ejs
This module is a rendering engine. Help us bind variable data back to the front page.
Installation is as follows:

npm install express --save
npm install body-parser --save npm install express-session --save npm install ejs --save

3. Log in and verify

Session state of the client can be marked on the server. Using this, we can achieve the client's login authentication. Session login authentication process substantially as follows: If the client requests a home page while logged in, the server redirects the request to the login page; client after login, the server needs to save logged record of the client, and give a duration of the activity, so that the next time the server requests the home page, you can log on to determine the status of the client, if the login status is valid, the client needs to return to the page directly, otherwise redirected to the login page.

For Session expiration time, if not set an expiration time Session, the server will default validity period based on their configuration, the long-term interaction with the server to delete the Session.

I posted the following example code, the interface is relatively simple, back-end server code comments written very clearly, and therefore no longer be explained.

The directory structure of the project are as follows:

Login page (login.html) code is as follows:

<!DOCTYPE html>
<html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> <style type="text/css"> </style> </head> <body> <form action="/login" method="POST"> 用户名: <input type="text" name="username"/> <br> 密码: <input type="password" name="pwd"/> <input type="submit" value="Submit"/> </form> </body> </html>

Home (home.html) code is as follows:

<!DOCTYPE html>
<html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> <div>用户名:<span><%= username %> </span> <a href="/logout">退出登录</a></div> </body> </html>

Server (app.js) code is as follows:

/**
 * Created by tjm on 9/7/2017.
 */

var express = require('express');
var app = express(); var session = require('express-session'); var bodyparser = require('body-parser'); // 下面三行设置渲染的引擎模板 app.set('views', __dirname); //设置模板的目录 app.set('view engine', 'html'); // 设置解析模板文件类型:这里为html文件 app.engine('html', require('ejs').__express); // 使用ejs引擎解析html文件中ejs语法 app.use(bodyparser.json()); // 使用bodyparder中间件, app.use(bodyparser.urlencoded({ extended: true })); // 使用 session 中间件 app.use(session({ secret : 'secret', // 对session id 相关的cookie 进行签名 resave : true, saveUninitialized: false, // 是否保存未初始化的会话 cookie : { maxAge : 1000 * 60 * 3, // 设置 session 的有效时间,单位毫秒 }, })); // 获取登录页面 app.get('/login', function(req, res){ res.sendFile(__dirname + '/login.html') }); // 用户登录 app.post('/login', function(req, res){ if(req.body.username == 'admin' && req.body.pwd == 'admin123'){ req.session.userName = req.body.username; // 登录成功,设置 session res.redirect('/'); } else{ res.json({ret_code : 1, ret_msg : '账号或密码错误'});// 若登录失败,重定向到登录页面 } }); // 获取主页 app.get('/', function (req, res) { if(req.session.userName){ //判断session 状态,如果有效,则返回主页,否则转到登录页面 res.render('home',{username : req.session.userName}); }else{ res.redirect('login'); } }) // 退出 app.get('/logout', function (req, res) { req.session.userName = null; // 删除session res.redirect('login'); }); app.listen(8000,function () { console.log('http://127.0.0.1:8000') })

This, session realize login verification is complete. The above example session is stored in the service memory, of course, can also be saved in a file or database, middleware can only need to configure session.

app.use(session({
    secret: 'secretkey',
    store: new MongoStore({
        db: 'sessiondb' }) }));

The above code is sucked MongoDB database to save the session, of course, some Session configuration, specific reference: https://www.npmjs.com/package/express-session

Guess you like

Origin www.cnblogs.com/qinlongqiang/p/11671412.html