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

Using Session in the Express framework to implement authentication at login

巴扎黑
Release: 2017-09-09 09:51:41
Original
1672 people have browsed it

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
Copy after login

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:


<!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>
Copy after login

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


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

The server (app.js) code is as follows:


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

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: &#39;secretkey&#39;,
  store: new MongoStore({
    db: &#39;sessiondb&#39;
  })
}));
Copy after login

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!

Related labels:
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template