Authentication and Authorisation on the web
Tags: mongodb, webdev, node, javascript
Published: 2020-07-20 13:55:05

#Introduction 🌈

This is a 4 part series covering all the concepts and code  you'll need to build a simple Authentication API with JWT, using Express and MongoDB.  

#The Naive Approach to building a Login/Registration System.

You've just had an awakening. You've figured out the next billion dollar app idea.

You get down to coding and manage to implement the headline feature of your app.

Now , all that stands in your way is implementing a system for users to register and login to your app. How would you build this system?

###Iteration 1
You figure that the best way to do this is to allow users to register with some basic fields. 

*Their username , email and password.*

Once , you receive a user's credentials , your backend processes that data and stores it in a Database.

When a user wants to login , if their email exists, your backend checks if the password entered by the user matches the password in the Database.

If it matches , The user is granted access to their account.

Now the first question that might pop up is,
 
**What if the user refreshes their page? How do we prevent our app from logging them out?**

You can manage a user's session with a Database. When a user logs in , store them in a sessions table. Check the sessions table to check if the user is logged in everytime they make a request.

  
![Alt Text](https://dev-to-uploads.s3.amazonaws.com/i/r20sw06l0uevoe8tqg78.png)



To make this process faster , you can use Redis which is an in-memory key-value store, i.e it does not save values like a traditional database.






#Improving our system's design (flaw-by-flaw) 🌈

**Saving Passwords in our Database as plain text**

When we register users in the system described above , we're storing the user's passwords as they are, without hashing. 

This creates a security vulnerability, if say, a hacker were to gain access to our Database.

###Hashing Passwords 

![Alt Text](https://dev-to-uploads.s3.amazonaws.com/i/v8mxzzvaudll3nf2tdvo.png)

A hash function generates a key-value pair. The key being a unique identifier and the value , being the original value.

In simple words , a hash function will scramble your original password into something else. 
This scrambled value is the key to your original password. 

This key will be stored in your database.

###Salting 

Okay , so now that the password is hashed , are we good to go?
 
Not really.

**What if multiple users have the same password?**

If multiple users have the same password , then they will also have the same hash. 

If a hacker manages to decrypt the hash of any one user's password , the credentials of all users with the same password are now at risk.

**Salting to the rescue ✨**

Salting in cryptography refers to simply appending or prepending some text to the original password.

Say , your password was originally **'brownmuffin20'**.

After salting , The password becomes **'brownmuffin20qi247mat742'** , after appending the salt **'qi247mat742'** to the original password.

The real icing on the cake is , even if a different user has the exact same password , the salt is always random.

So while user 1's password after salting will be **'brownmuffin20qi247mat742'**

User 2's password after salting would be

**'brownmuffin20p423dh92p32f'**


![Alt Text](https://dev-to-uploads.s3.amazonaws.com/i/ul11ewkppbrd8wb25fjz.png)

Therefore , Users with same passwords have different salts. Therefore they end up with different hashes. So..

*Even if a hacker manages to gain access to your Database , your account's credentials will still be safe.*

[Read more about salting here](https://auth0.com/blog/adding-salt-to-hashing-a-better-way-to-store-passwords/)

###Avoid the overhead cost of using a session store. 🌈

**Sessions vs Tokens (The Battle of Authentication)** 🙉

What this post has covered so far is "Authorization".

Authorization is basically determining if you are authorised to access some particular data , eg. your Facebook profile.
 
Authentication is the next step. Authentication is basically checking if you are who you really claim to be.

*Let's understand this with a simple example.*  

Say you've been invited to a conference. The conference is taking place at the Marriott.

At the conference , there are a number of talks and group discussions taking place and to be allowed inside any of these events , you need to be *Authorised*.

 i.e You need to go to the bench and register yourself as an attendee. At the bench , you are registered and written down in a register.

Now , when you wish to attend a talk , a person at the entrance will check your name in the register and allow you inside if your name exists.

Let's say , your friend Alisha is staying at the Marriott too but has not been invited to the conference.
 
However she knows that you're here for the conference with an invitation and she can enter any talk she wishes to , using your name. This is where authentication comes in.

The people hosting the conference are aware that people staying at the hotel may enter using somebody else's name so , they assign each person registering at the conference , a secret. 

Without this secret , people who aren't registered at the conference cannot enter.

**Simplifying the authentication process** 🌈

If you've gone through the story , you might be thinking to yourself,

Rather than having someone checking if the user exists in the register , everytime they want to attend a talk , Why not give each registered user , an ID card with their photograph (For authentication). 

This means , that the people hosting the conference no longer have to keep track of which of their attendees are present at the event. 

You might be getting some idea of where I am going with this story.

Is there some kind of system where , every time a user logs in - My server can give them a token that they can store in their browser (Cookies , LocalStorage) , rather than my server having to keep track of logged in users? 🌚

You bet , There is! 🌝

**Say hello to Token Based Authentication.** 👋🏼

A System that's the perfect example of token based authentication is used widely is JWT. 

JWT stands for JSON Web Tokens and we'll learn all about them and how to implement them in the final part of this series.



[Read about Tokens vs Sessions here](https://medium.com/@theflyingmantis/session-vs-jwt-token-based-authentication-2e85ff6c8f42)

That's about it for the first part folks! 🌈

In the [next part](https://dev.to/aritik/connecting-to-mongodb-using-mongoose-3akh) , we'll set up a Simple Express Server and connect it to our MongoDB Database. We'll also learn how to write Schemas using Mongoose (Object Document Mapper). 🌟