Authentication in brief

There are many vulnerabilities in web. MySpace suffered from XSS(Cross Site Scripting). Twitter has suffered many data leaks. But data leaks is something that can be prevented as well as protected with many restrictions.Security and authentication on server or client has always been a major concern to web security.And adding client side security has been better option nowadays.

Authentication is the major factor for the security in any web or mobile applications. Authentication make our website secured against various vulnerabilities.It is also important to preserve many data for security purpose.

Image for post
Image for post
Photo by Jose Fontano on Unsplash

There are many types of authentication. But basically, they are classified into 2 types.They are:

1. Stateful Authentication.

We can take back the authentication an session on IDP (Internet Provider) any time.It is used for applications that do not require scalability too much and do not occupy much memory space.


Firstly most of the authentication are created in backend portion.And the corresponding session id is sent to the client.Each time the client makes a request to the server, the server locates the session memory using the reference Id from the client and finds the authentication information.

Image for post
Image for post
Stateful Authentication(fig from Kenneth Choi)

In this authentication,as the number of logged-in users increases, the more server resources are occupied.It is not possible for scaling.It is difficult for third party to use credentials. To overcome its features, Stateless authentication has come into practice.

2. Stateless Authentication

The session expiration time is set when authentication token in made. We can take back the authentication an session on IDP (Identity Provider) any time.


Stateless authentication stores the user session data on the client side (browser). And the data is authenticated by the server.The data is signed by the key of Identity Provider to ensure the integrity and authority of the session data.Identity Provider is used to create and manage information of identity and provides authentication .

Image for post
Image for post
Stateless Authentication(Kenneth Choi)

In this authentication,as the number of logged-in users increases, the server resources remains same as the key is renewed over time.It is possible for scaling.It is difficult for third party to use credentials.It is currently used widely. The most popular of it is JWT(JSON Web Token).It cannot revoke session any time. And it is more complex for solving.

Many of you get confused with the term called IDP(Identity Provider).We will talk about it.

Why token based authentication stateless?

Token-based authentication can be used to enable a stateless architecture but can also be used in stateful architectures. For example, a JWT can contain all the necessary session data, encoded directly into the token, in which case it supports a stateless architecture. JWT can also be used to simply store a reference or ID for the session, in which case the session data needs to be stored server-side, making the architecture stateful.

Identity Provider

It is simply used to provide authentication and offers maintenance and provides environment for web and various related features.

According to wikipedia.

Identity Provider (IdP or IDP)is a system entity that creates, maintains, and manages identity information for principals while providing authentication services to relying applications within a federation or distributed network

It is majorly responsible for providing web the basic identity and various security features.

It is of 3 types:

1.IndieAuth Identity Provider

2.OpenID provider

3.SAML identity provider


HTTP stands for Hyper Text Transfer Protocol.It is a application layer protocol that allows the communication between client and server.HTTP is also stateless.

Every time you get to the new link, the protocol looses everything(your login data). For example,if you login and get redirected to you home page in any site. If you move to any other pages of website,it looses your identity that you have (like username,password while logging in). That is where cookie comes in to remind your data to the protocol.

Remember HTTP and HTTPs are different

HTTPs where s stands for secure for any connection.It allows better security than HTTP and is in use nowadays.


Cookie is a file or part of file that is used for storing the temporary data on your local computer. It is basically a short and quick memory to remind HTTP about something that is stored and is necessary until user is active in the website.

Session based Authentication

It is a authentication based on session.In this, the data is stored on cookie.Cookie is something that is used for storing the data on local computer.Cookies stores the id of the session and sends the data to the user browser.Then the browser puts the request to get the authentication.


It is the secutiry that has JSON token in it.JSON stands for Javascript Object Notation.It is simply a format for the representation of the data.Its example is given by:


In the following, first name are just the attributes and item after colon is the value.

JSON web token creates a token of JSON to create a gateway or the temporary key for the web access inside the site.

JSON Web Token(JWT)

JWT offers a basic authentication in your web.It is a stateless authentication method that creates a token temporarily for a accessing a website.We can say it as a temporary lock for a login system to prevent unauthorized access.

JWT consists of 3 parts concatenated with . like

header_part.payload_part_signature_part//actually each part consists of combinations of alphabets and numbers (like X124ddfe)
  1. Header

It describes the type of token and signing algorithm being used.


It consists of data or identities of user information within it.


It consists of the encoded header, the encoded payload, a secret, and lastly, the algorithm which is specified in the header.

To create a JWT authentication we need to create it through 2 functions

  1. jwt.sign()
  2. jwt.verify()
//import jwt
const jwt=require(‘jsonwebtoken’);
//Simply to create token
const token=jwt.sign({_id:’abc123},’secretkey’,{expiresIn:’7days’});

console.log(token); //Get data from token const
//NOTICE:Did you notice that the secret-key is same in both the cases.It is a key to verify
Learn more about it at jwt.io


Bcryptjs offers a good way of hashing your password. It is used to completely encrypt your password that no any other (not even the developer are allowed to view the password until the proper decoding method is cracked). Bcryptjs is a great security tool to ensure the proper security to your password.It uses a method called hashing to get the encrypted password.To again get the password the same hashing is done to ensure the correct password.

To Register: Create Hashed PasswordTo Login:Hashed the re-entered password with the same hashing to    
match the previous hashed password

There are some tools that we need to know what its component are


Hashing is the method to taking a data to encode into something with a set of rules.It is done using a hash function.

Wikipedia defines hash function as

A hash function is any function that can be used to map data of arbitrary size to fixed-size values. The values returned by a hash function are called hash values, hash codes, digests, or simply hashes.

Hash function index a code to a table by a certain rule that generates a unique set of code.

Its basics function is done by:


Its code structure is given below.

//import bcryptjs
const bcrypt = require('bcryptjs');
bcrypt.genSalt(10, function(err, salt) {
bcrypt.hash("B4c0/\/", salt, function(err, hash) {
// Store hash in your password DB.

genSalt is a keyword that is used to generate the salt for the hashing.The sal obtained is used for hashing with ‘bcrypt.hash’. 10 is a number used in hashing for the number of times hashing functions hashes a particular input.

To check a password:

// Load hash from your password DB.bcrypt.compare("B4c0/\/", hash, function(err, res) {
// res === true
bcrypt.compare("not_bacon", hash, function(err, res) {
// res === false
bcrypt.compare("B4c0/\/", hash).then((res) => {
// res === true

Learn more at https://github.com/dcodeIO/bcrypt.js/


PassportJWT is a starategy for authentication JSON Web Token(commonly known as JWT).It claims to offer 500+ authentication in your web including google,facebook, etc

It is created as :

new JwtStrategy(options, verify) 

option is simply an object containing options to control how the token is extracted from the request or verified.

verify is a function with the parameters(jwt_payload,done)

payload is a programming term used to denote that it consists of some information about that topic.Strategy carries out the strategies for passport.(maybe..)

We have secret key in passportjwt called SecretOrKey(can be of any name as it is not keyword but official documentation uses this word to denote) for storing a access for the passport.

just basic format is

passport.use(new JwtStrategy(opts, function(jwt_payload, done) {}

It is used with 3 coding setups(for passport.js file)

const JwtStrategy = require('passport-jwt').Strategy,
const ExtractJwt = require('passport-jwt').ExtractJwt;
//opts has 2 objects
var opts = {}
opts.jwtFromRequest = ExtractJwt.fromAuthHeaderAsBearerToken();
opts.secretOrKey = 'secret';

passport.use(new JwtStrategy(opts, function(jwt_payload, done) {
User.findOne({id: jwt_payload.sub}, function(err, user) {
if (err) {
return done(err, false);
if (user) {
return done(null, user);
} else {
return done(null, false);

jwtFromRequest is a local term(like secretOrKey as stated above) that is use to get data from header authorization. The most preferred way to get the token is by using in the form

Bearer    eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpZCI6IjVmNWNlODQxOTA2NGU3MmQ0MmVlZDQ0YiIsIm5hbWUiOiJBYWthc2giLCJhdmF0YXIiOiIvL3d3dy5ncmF2YXRhci5jb20vYXZhdGFyLzI2NjI0MWE5YzRlMjRjNGEwODJjYTBlYWI5ZjUxOGEzP3M9MjAwJnI9cGcmZD1tbSIsImlhdCI6MTYwMDEzNTM2MCwiZXhwIjoxNjAwMTM4OTYwfQ.WUG8XD9WjK7rs9-w4yPh-XL5mzsY2PxzTG8WS4fbmOc

The random strings that appears after bearer is a token(imagine anyone remembering to get access).

There are other way to extract the header too, but I really don’t know why the format of using Bearer is used for the token representation.

For any route file

//import passport
const passport = require('passport');
router.get('/any', passport.authenticate('jwt'{session:false}),(req, res) => { //can be anything

And at last,setup the server file

// Passport middleware
// Passport Config

Learn more from http://www.passportjs.org/packages/passport-jwt/

Written by

hungry for knowledge and sharing

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store