The purpose of this article is to show how to implement authentication just using express-session module.

1. Authentication

It is important to distinguish between authentication and authorization. Authentication is the process of verifying the identity of the user 401 Unauthorized and authorization dictates what the user can see and do when it is authenticated 403 Forbidden.

To overcome the stateless nature of HTTP requests, there is two main options:

  •  session-based authentication (stateful, state is stored in the server memory)
  • token-based authentication (stateless, state is stored inside the token on the client-side).

Session-based authentication flow:

  • The user submits the login form and sends credentials (username and password) to the server,
  • The server checks credentials in the database,
  • If credentials are good, the server creates the session and store it in the database,
  • The server sends the cookie with session ID back to the user,
  • The user sends the cookie with each request,
  • Server validate session ID against session in the database and grants access,
  • When the user logout, the server destroys the session.

Let´s go . . .

Open up the file ‘app.js’ and let us set up the server.

const exp=require('express');
const app=exp();
app.listen(3000,()=>{
console.log('Server listening on port 3000');
});

Now we require modules:express-session and uuid (uuid for ramdom ID).

const exp=require('express');
const app=exp();
var genuuid=require('uuid/v4');// '/v4' for version 4
const session=require('express-session');
app.listen(3000,()=>{
console.log('Server listening on port 3000');
});

Now we make express-session as middle-ware and add few routes.

//Requiring modules.
const exp=require('express');
const app=exp();
var genuuid=require('uuid/v4');
const session=require('express-session');
//Making session as middleware for all routes.
app.use(session(
{ name:'SessionCookie',
  genid: function(req) {
      console.log('session id created');
    return genuuid();}, 
  secret: 'Shsh!Secret!',
  resave: false,
  saveUninitialized: false,
  cookie: { secure: false,expires:60000 }
}));
//Routes
app.get('/',(req,res)=>{
res.send('<h1>home page</h1>');
});
app.get('/secret',(req,res)=>{
res.send('<h2>You have accessed Secret Page</h2>');
});
app.listen(3000,()=>{
console.log('Server listening on port 3000');
});

Make sure cookie.secure property is set to false because we will be using HTTP and it has not encryption enabled so if cookie.secure=true then cookie with requests are not sent to the server if HTTPS is not enabled and thus we won’t be able to identify session.

Now when we first visit our site a session will be created but as we have set cookie.saveuninitialized=false then cookie won’t be issued unless we make changes to a session. lets run the application to observe.

C:/SessionApp/node app.js
Server listening on port 3000
session id created

If we click the little ‘i’ button near our address bar we see that no cookies have been issued.

Explanation:

HTTP requests are stateless. It means they don’t help server to identify who sends the request. So servers create session(server side storage) for each user which holds data about the user and this session has an ID.

To help server know which session belongs to which user,it creates a cookie on user’s browser(a temporary file) which contains encoded value of an id to help server identify session. So even having cookie the user can’t decode the value and get the session id.

when we first make a request to some website then this website has no information about the incoming request,to track about the user.

Now we will create a ‘login’ route which when visited stores data on session and if the cookie is not set then a cookie will be issued because now we have started to make changes in session so to keep a track of it a cookie is sent to user having name ‘SessionCookie’ and its value as told earlier will be encoded.

app.get('/login',(req,res)=>{
req.session.username='Brice';
res.send('<h4>Logged in successfully</h4>');
});

If we now, run our app and visit login route we will see the cookies.

C:/SessionApp/node app.js
Server listening on port 3000
session id created
session id created

We see the message of session id being created two times.First one was created when first visited our site,so we had no cookie to identify our session but when we visited the login route we see another message because this incoming request also didn’t carry cookies with it, so a cookie is issued so now our session is no longer uninitialized.

Our session is now working. Yet we want ‘secret’ route which only can be visited if user is authenticated and the username is “Brice”

app.get('/secret',(req,res)=>{
if(req.session.username=='Brice')
    res.send('<h2>You have accessed Secret Page</h2>');
    res.redirect('/');
});

what the above code does : it checks the appropriate session meaning decoding the cookie value if set in client,using it to identify appropriate session by session id and if values match in our if statement our server responds with sending HTML otherwise it redirects the user to home page or root route.

This was just a simple example to demonstrate how you can make user login so that when the cookie expires you lost the session. You can use sessions to store user id for example and check if user id exists then show respective routes.

By Shabazz

Software Engineer, MCSD, Web developer & Angular specialist

Leave a Reply

Your email address will not be published. Required fields are marked *