Nodejs----Login Verification

Source: Internet
Author: User
Tags session id

1. Write in front

When we login to a website, without logging out of the case, we closed the site, over a period of time, open the site again, 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. What does the server store our login status with? The answer is session, where the service can record the status of each client connection through the session. About the principle of the session, in this is not much to say, this article mainly introduces in the Express framework, how to use the session to achieve user login authentication.

2. Environment configuration

In the node environment, there is no integrated Express and Session library, so you need to install, first go to build a project directory, and then in the project root directory, with the following command to install four modules.
1) Express
This module allows us to quickly build a WEB development framework.
2) Body-parser
The module is the middleware of the Express module, which allows us to parse the body data sent by the browser.
3) Express-session
The module is also the Express module middleware, which allows us to handle the client session.
4) Ejs
The module is a rendering engine. It is convenient for us to bind the background variable data to the foreground page.
Install the following:

install express --savenpm install body-parser --savenpm install express-session --savenpm install ejs --save
3. Login and Verification

Session can flag the state of the client on the server. With this, we are able to implement client login verification. The process of Session login verification is basically: if the client requests the home page without logging in, the server redirects the request to the login page, and after the client logs on, the server needs to record the login status of the client and give an active period, so that the next time the server requests the home page, will be able to determine the client's login status, if the login status is valid, directly return to the client needs the page, otherwise redirect to the login page.

For the session expiration time, if you do not set the session expiration time, the server will be in its own configuration in accordance with the default validity period, the long-term does not interact with the server Session to delete.

The following example code, the interface is relatively simple, the server background code comments written very clearly, so it is no longer explained.

The directory structure of the project is as follows:

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

<! DOCTYPE html><Htmllang="EN" ><Head><Metacharset="UTF-8" ><Title>title</Title><StyleType="Text/css" > </Style></Head><Body><Formaction="/login"Method="POST" > Username:<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><Htmllang="EN" ><Head><Metacharset="UTF-8" ><Title>title</title></head> <body> < Div> User name: <span>< %= username%> </ span> <a  Href= "/logout" > Exit login </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 the engine template for rendering App.set (' Views ', __dirname);Set the directory for the template App.set (' View engine ',' HTML ');Set resolution template file type: Here is the HTML file App.engine (' HTML ',Require' Ejs '). __express);Use the Ejs engine to parse the EJS syntax App.use (Bodyparser.json ()) in the HTML file;Using the Bodyparder middleware, App.use (bodyparser.urlencoded ({extended:true}));Use session middleware App.use ({secret:' Secret ',To sign the cookie associated with session ID Resave:True, saveuninitialized:FalseWhether to save the uninitialized session cookie: {maxAge:1000 *60 *3,Set the session's effective time, in milliseconds},});Get the login page app.get ('/login ',functionReq, res) {Res.sendfile (__dirname +'/login.html ')});User Login App.post ('/login ',functionReq, res) {if (Req.body.username = =' admin ' && req.body.pwd = =' admin123 ') {req.session.userName = Req.body.username;Login successful, set session Res.redirect (‘/‘); }else{Res.json ({ret_code:1, Ret_msg:' Account or password error '});If login failed, redirect to login page}});Get Home App.get (‘/‘,function (Req, res) {if (req.session.userName) {//determine the session status, if valid, return to the home page, Otherwise go to login page res.render ( ' home ', {username:req.session.userName});} else{res.redirect (//exit App.get ( '/logout ', function (req, res) {req.session.userName = null; //Delete session res.redirect ( ' login ');}); App.listen (8000,function ( Span class= "Hljs-params") {console.log (              

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

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

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

Nodejs----Login Verification

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.