First of all what’s the difference between Authentication and Authorization?
Authentication is a way to validate the identity of a registered user attempting to gain access to an application, API or any other data resource. In contrast, once you are authenticated, authorization is about deciding whether an individual is permitted to perform a given action on a specific resource.
To protect sensitive information and to prevent our websites or applications from being compromised we need to authenticate and authorize a user. To do so we can follow the below steps:
1) Setting up a the File Structure
- user.js -/routes
- verifyToken.js - app.js
2) Initialize npm and install required packages
We will first initialize npm so we can track the dependencies our server has. The flag “-y” initializes npm with default parameters.
npm init -y
Now we will install all the packages that are required using npm install command . The “--save” flag adds the dependencies in package.json file.
npm install --save express mongoose body-parser jsonwebtoken bcryptjs
3) Start the server and connect our MongoDB database.
Your app.js file should look something like this:
I personally prefer nodemon to start my server so that we don’t have to restart our server after every small change. nodemon does it automatically for you.
To install nodemon execute this in your terminal
npm install -g nodemon
Run “ nodemon app.js “ command in your current directory on your terminal. If you get the message “App started”, Voila!!! You have started your server.
4) Setup our User Schema
We need to define our User Schema for our user in our database. The user needs to have three basic information- email, username and a password.
5) Add a post route for signup
For creating a new user ,we first have to setup a post route to “/register”. While creating a new user account we will first check for two conditions
i)The email should be unique. If the email is already present in database we return a error.
ii)Similarly, the username should also be unique. If the username is already present in database we return a error.
If these conditions are satisfied we need to hash the password using bcryptjs and store it in the database.
Hashing is the act of converting passwords into unreadable strings of characters that are designed to be impossible to convert back, known as hashes.
Hashing a password is important because if somebody has access to the database he/she can directly see the password it can compromise user security. You can read more about bcryptjs here( docs).
Your “auth.js” file should look like this now.
6) Add a post route for Login
For login ,we first have to setup a post route to “/login”.
We first check if the email id is present in the database. If we find a user with the email provided we compare the password using bcrypt.compareSync(plainPassword , hashedPassword)
If the email and password is correct we create a JSON Web Token(JWT) for the user and we add it to our header under the field “auth-token”. We create a JWT token using the jwt.sign(tokeninfo, aSecretCode) function. You might want to save the Secret Code as an environment variable. But for simplicity I have directly included it in my code.
You might be wondering what is JSON Web Token?
Well, JSON Web Token (JWT) is an open standard that defines a compact and self-contained way of securely transmitting information between parties as a JSON object. This information can be verified and trusted because it is digitally signed. In simple words we can restrict certain pages of the website using JWT. If a valid token is found in the header then only the user can access such pages.
So your final “auth.js” file including your route for signup and login should look like this.
6)Creating a Secret route and verifying a token
We will create a sample route which can only be accessed if a valid user is signed in.
Now lets create our verifyToken function. This function extracts the token from the header and then verifies it using jwt.verify() . If the token is unavailable we throw a 401 error “Access Denied”. If the token is correct we execute the next() function to move forward to execute the next instruction. Such type of a function is called a middleware.
7) Testing with Postman
So we have setup our code. All we have to do is test and see if everything works fine or not. I am using an application called Postman through which i can send requests(Link to Postman).
First start up your server in case you haven’t.
i) Lets create a new User. We will send a post request to the URL http://localhost:3000/register
We can see that a new user has been created and added to our database.
ii) Lets try to Login using the above credentials. We will send a post request to the URL http://localhost:3000/login
We can see the message Login successful with the generated token for the particular user.
iii) Lets try to access the secret page. We have to send a get request to URL http://localhost:3000/
We add a “auth-token” as a key to the header with the value of the token from above login route message. After this when we send a request to the URL and we get the message “This is a secret route”.
So we have successfully learnt how to Authenticate and Authorize a user on our Website. I have uploaded the code in my Github repository. Check it out https://github.com/atharvarockx/Authentication/
I hope you after reading this blog you get a better idea about how authentication and authorization works.
This is my First Blog and I will be working on more such blogs to help out. If you liked the article, you can 👏 the story and share it with others.