Home  >  Article  >  Web Front-end  >  Using Session in the Express framework to implement authentication at login

Using Session in the Express framework to implement authentication at login

巴扎黑
巴扎黑Original
2017-09-09 09:51:411476browse

This article mainly introduces how to use Session to implement user login authentication in the Express framework. For those who are interested, let’s take a look at the knowledge related to express session login verification.

1. Write in front

When we log in For a website, we close the website without logging out. After a while, when we open the website again, we will still be logged in. This is because when we log in to a website, the server will save our login status until we log out or the saved login status expires. So how does the server store our login status? The answer is Session, through which the service can record the status of each client connection. I won’t say much about the principle of Session here. This article mainly introduces how to use Session to implement user login authentication in the Express framework.

2. Environment configuration

In the Node environment, there is no integrated library for Express and Session, so it needs to be installed. First enter the establishment A project directory, and then use the following commands to install four modules in the project root directory.

1) Express

This module allows us to quickly build a web development framework.

2) body-parser

This module is the middleware of the Express module, which facilitates us to parse the body data sent by the browser.

3) express-session

This module is also the Express module middleware, which facilitates us to process the client's session.

4) ejs

This module is a rendering engine. It is convenient for us to bind background variable data 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. Login and verification

Session can Mark the client's status on the server. Using this, we can implement client-side login verification. The process of session login verification is roughly as follows: if the client requests the homepage while not logged in, the server will redirect the request to the login page; after the client logs in, the server needs to record and save the client's login status and give a Activity period, so that the next time the server requests the home page, it can determine the client's login status. If the login status is valid, it will directly return to the page the client needs, otherwise it will redirect to the login page.

Regarding the Session expiration time, if the Session expiration time is not set, the server will delete Sessions that have not interacted with the server for a long time according to the default validity period in its own configuration.

The example code is posted below. The interface is relatively simple, and the server background code comments are clearly written, so I will not explain it again.

The directory structure of the project is as follows:

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





  
  Title
  

用户名:
密码:

Home page (home.html) The code is as follows:





  
  Title

用户名:<%= username %> 退出登录

The 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')
})

At this point, the session realizes login The verification is complete. In the above example, the session is saved in the service memory. Of course, it can also be saved in a file or database. You only need to configure the session middleware.


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

The above code saves the session to the MongoDB database. Of course, there are some configurations for the Session. For specific reference:

https://www .npmjs.com/package/express-session

The above is the detailed content of Using Session in the Express framework to implement authentication at login. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn