Different ways for User Authentication & Authorization with NodeJS Part - 1
Tags: webdev, javascript, beginners, tutorial
Published: 2021-11-20 20:15:09

First let us get over with the debate of **Authentication** vs **Authorization**.

##Authentication
It is the process to verify if the user is telling the truth. For example: when we log into our account with some username and password, the process of verifying those credentials with the stored information in database and knowing that the user is really whom he/she claims to be is called Authentication.

##Authorization
It is a security process to know what information user has access to. Giving someone permission to download a particular file on a server or providing individual users with administrative access to an application are good examples of authorization.

In this article we are going to look into two different methods of User Authentication with NodeJS
* Sesssion Based Authentication
* Token Based Authentication


Prerequisites
* [NodeJS](https://nodejs.org/en/)
* [MongoDB](https://www.mongodb.com/) 
(You can use an Atlas account or local mongodb connection)

Setup a new NodeJS project using `npm` or `yarn` whatever you like.

#Session Based Authentication

[![session-auth.png](https://i.postimg.cc/ncLPwDcm/session-auth.png)](https://postimg.cc/WtQ8dtZp)

This image very simply summarizes the session based authentication. Let's implement it in code and understand better.

Execute the following line of code on your terminal within your project directory.

`npm install express express-session mongoose connect-mongo`

express - For creating our server
express-session - For creating our session based authentication
mongoose - To Connect to our MongoDB Database
connect-mongo - For storing our sessions in MongoDB Database

```javascript
const express = require('express');
const app = express();
const mongoose = require('mongoose');
const MongoStore = require('connect-mongo');
const session = require('express-session');

await mongoose.connect('your_mongo_url', (err, db) => {
            console.log('MongoDB Connected....');
      });

app.get('/', (req,res)=>{
    res.send('<h1>Hello World!</h1>')  
})

app.listen(5000, () => console.log(`Server 🔥🔥🔥 up on 5000`));
```

This block of code will make our server up and running on Port 5000. So if you now visit [http://localhost:5000/](http://localhost:5000/) you will see the desired result.

Now let us configure the MongoDB Store for session storage.

```javascript
app.use(session({
    secret: 'fiwafhiwfwhvuwvu9hvvvwv', // Never ever share this secret in production, keep this in separate file on environmental variable
    resave: false,
    saveUninitialized: true,
    cookie: { maxAge: oneDay },
    store: MongoStore.create({
        mongoUrl: 'your_mongo_url'
    })
}));
```

This block of code used the express-session package to create an empty Session object for a request. 
[Refer](https://stackoverflow.com/questions/40381401/when-to-use-saveuninitialized-and-resave-in-express-session) to this link to understand about saveUninitialized and resave properties in the object.

So this will create a new empty session inside our mongodb database with a collection name sessions.

Let's create a login route for user 

```javascript
app.post('/login', async (req, res) => {
    const { username, password } = req.body;    
try {
        let user = await User.findOne({ email: username })
        req.session.userId = user.id;

        console.log(req.session);

        res.redirect('/dashboard')

    } catch (err) {
        console.log(err);
        res.json({ msg: 'Server Error! Please reload page' });
    }
})
```
Now this block of code is important. Now when the user logs into its account with username and password we send that request to our server and store the request in the session. `req.session.userId` is storing the unique _id of the user in the session and server creates a unique session id which is placed in the cookie which will be sent back to the client and stored in the client's browser as. Now whenever the client will make any request to the server the header will contain this cookie and we at server side are able to authenticate that particular user using that cookie in the header and obtaining the userId of the user.

```javascript
module.exports.authentication = async (req, res, next) => {
    const userId = req.session.userId;
    if (!userId) {
        return res.redirect('/login?q=session-expired');
    }
    try {
        let user = await User.findById(userId);
        if (!user) {
            return res.redirect('/login?q=session-expired');
        }
        next();
    } catch (err) {
        console.log(err);
        res.json({ msg: 'Server error. Please reload page after sometime' })
    }
};
```

We can create this type of middleware function where for every request on protected routes like dashboard, booking history, payment routes etc we can authenticate the user and display the correct data according to the user. 

###Advantages of Session Based Authentication
* Cookies are small-sized values, easy to use and implement and can revoke the validity of the cookies.

###Disadvantages of Session Based Authentication
* Sessions are stored in server/database and not on client side thus it makes it really difficult to scale the project when there is a huge number of requests simultaneously.

This is where token based authentication (a modern and scalable solution) comes in. It solves the biggest headache with the session authentication that tokens are stored in client's browser thus making it really simple to scale the application.
Stay Tuned for part 2 where we talk all about the Token Based Authentication.

[![Buy Me A Coffee](https://cdn.buymeacoffee.com/buttons/default-orange.png)](https://www.buymeacoffee.com/lavishgoyal)