Express + Session Implementing Logon Authentication

1. Write in front

When we log on to a website, without logging out, we shut down the website, and after a period of time, open the website again, it will still be logged in. This is because when we log on to a website, the server will save our login status until we log out or the saved login status expires. How does the server store our login status? The answer is Session, through which services can record the status of each client connection. The principle of Session is not much to say here. This paper mainly introduces how to use Session to realize user login authentication in Express framework.

2. Environmental configuration

In Node environment, there is no library integrating Express and Session, so it needs to be installed. First, enter to establish a project directory, and then install four modules in the project root directory using the following commands.
1) Express
This module enables us to quickly build a Web development framework.
2) body-parser
This module is the middleware of Express module, which is convenient for us to parse the body data sent by browser.
3) express-session
This module is also the middleware of Express module, which is convenient for us to deal with the session of the client.
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 status of the client on the server. With this, we can achieve client login validation. The process of Session login verification is roughly as follows: if the client requests the home page in an unregistered state, the server redirects 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 an active period, so that the next time the server requests the home page, it can judge the client's login status. If the login status is valid, return the page needed by the client directly, otherwise redirect to the login page.

For the expiration time of Session, if the expiration time of Session is not set, the server will delete the Session which is not interacting with the server for a long time according to the default expiration date in its configuration.

The example code is pasted below, the interface is relatively simple, and the server background code comments are clearly written, so it is no longer explained.

The catalogue structure of the project is as follows:

The 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">
        User name: <input type="text" name="username"/>  <br>
        Password: <input type="password" name="pwd"/>
        <input type="submit" value="Submit"/>
    </form>
</body>
</html>

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

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
    <div>User name:<span><%= username %> </span>  <a href="/logout">Logout</a></div>
</body>
</html>

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');

// The following three lines set up the engine template for rendering
app.set('views', __dirname); //Directories for setting templates
app.set('view engine', 'html'); // Set the parse template file type: here is the html file
app.engine('html', require('ejs').__express); // Parsing ejs syntax in html files using ejs engine

app.use(bodyparser.json()); // Using the body parder middleware,
app.use(bodyparser.urlencoded({ extended: true }));

// Using session Middleware
app.use(session({
    secret :  'secret', // Sign session id-related cookie s
    resave : true,
    saveUninitialized: false, // Save uninitialized sessions
    cookie : {
        maxAge : 1000 * 60 * 3, // Set the effective time of session in milliseconds
    },
}));

// Get the login page
app.get('/login', function(req, res){
    res.sendFile(__dirname + '/login.html')
});

// User login
app.post('/login', function(req, res){
    if(req.body.username == 'admin' && req.body.pwd == 'admin123'){
        req.session.userName = req.body.username; // Log in successfully, set session
        res.redirect('/');
    }
    else{
        res.json({ret_code : 1, ret_msg : 'Error in account or password'});// If login fails, redirect to login page
    }
});

// Get home page
app.get('/', function (req, res) {
    if(req.session.userName){  //Judge session status, if valid, return to home page, otherwise go to login page
        res.render('home',{username : req.session.userName});
    }else{
        res.redirect('login');
    }
})

// Sign out
app.get('/logout', function (req, res) {
    req.session.userName = null; // Delete session
    res.redirect('login');
});

app.listen(8000,function () {
    console.log('http://127.0.0.1:8000')
})

At this point, session implementation login validation is completed. The above example session is saved in service memory, of course, it can also be saved in files or databases, just need to configure session middleware.

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

The above code saves sessions to the MongoDB database. Of course, there are some configuration of Session. For specific reference: https://www.npmjs.com/package/express-session

Keywords: Javascript Session npm JSON Web Development

Added by ToddAtWSU on Sun, 26 May 2019 21:13:25 +0300