Node-Js Authentication, In the easiest way possible!!

I have been into Web Development for a long time now, and one thing that always used to feel super difficult to me is authentication! Yes implementing Signup and Sign in features to my website. So after watching a bunch of tutorials on youtube I finally managed to understand it really well! And to reduce your efforts of going through a million videos on You-Tube I'm writing this blog. Follow along and you will find the easiest approach to implement authentication.

What we will use?

  • Node-js

  • Express

  • JSON Web Token

Init an empty node project

npm init -y

Install all the packages

npm install express jsonwebtoken

What are we trying to achive?

const POSTS = [
    {
        username: "saras",
        content: [1, 2, 3]
    },
    {
        username: "harsh",
        content: [4, 5, 6]
    }
]

We want to build a route in express which will give us the content array based on the username. If the signed in user is saras then we want to return the [1,2,3] Array from the POSTS Array.

First lets start by importing all the packages.

const express = require("express")
const app = express();
const jwt = require("jsonwebtoken")
app.use(express.json())
const SECRET = "ldklajfkdsfjokjfgoijoih12ldfjho2309r83rnasgfaiu"

Let's Write the login endpoint

app.post('/login', (req, res) => {
    const usernamme = req.body.username;
    const user = { name: usernamme }
    const accesTOKEN = jwt.sign(user, SECRET);
    res.json({ token: accesTOKEN })
})

If you see we are not doing a lot in this endpoint. we are just accepting username from body storing it into a object called user and then creating a jwt Token about it. But what is jwt and how does it work.

So to take a Top-down view imagine it as a encrypted key which contains the data you give it. And whenever in need you can get that data from the token.

const accesTOKEN = jwt.sign(user, process.env.TOKEN);

jwt.sign() takes 2 arguments first is the data that token should store and secondly a secret key based on which the token and the data will be encrypted. The secret key can be any random string. Secret key should not be exposed anywhere in the code it should be put into a .env file.

Lastly jwt.sign() will create a token and we return it in the response.

As you can see if we execute this endpoint by providing a value for username it returns us a token which is again a long string. But that string contains the data that we have provided.

Go to jwt.io

As you can see we enter the token in the encoded section and it returns us the decoded data of that token which is an object containing name of that user.

And now we are almost done with the Authentication functionality. But there is still a bit that we need to do.

Now we write a specific type of function which we call a middleware function. A middleware function gets executed in between the request going to the server and response comming from the server. And in this function we check whether or not the user is authenticated, and if it is only and only then the response is sent!

Middleware Function is like a guard on the gate who checks your tickest and only then allows you to enter the venue.

function authenticateUser(req, res, next) {
    const authHeader = req.headers['auth'];
    const token = authHeader && authHeader.split(' ')[1];
    if (token == null) res.status(401);
    jwt.verify(token, process.env.TOKEN, (err, user) => {
        if (err) {
            res.status(401);
        }
        req.user = user;
        next()
    })
}

In this function we are receving the token in the headers and then we are verifying it using jwt.verify() function which takes 3 arguments first is token second is the SECRET KEY and third is a function. That function gives back the data assigned in the token. req.user = user stores the data for further use.

Now lets build a route which will get user specific data from POSTS array.

app.get('/post', authenticateUser, (req, res) => {
    res.json(POSTS.filter(post => post.username == req.user.name))
})

As you can see we are passing the middelware function beforere returning the response. This endpoint will be only executed if correct token is assigned in headers.

Once it Gets the correct token it filters out the posts that have the name specified in the token. And returns only those specific posts from the POST array.

And there we have it a very basic autheniticatin system by using node-js and JWT. There is a lot to improve here like you would like to take more credentials while logging-in or you may want to store the users in a data base like Mongo-DB. But for now I hope you got an in-general idea of the whole process!

If you want to see the Full code you can check out my Repositary --> https://github.com/The-Saras/Full-Stack-Web-Dev/blob/main/Authentication/simple-authentication/app.js

Thanks a lot for reading see you in the next one.