How to Authenticate and Authorize User Using JWT in NodeJS


Authentication and authorization is the fundamental idea of laptop safety. You use your credentials (comparable to a username and password) in order to end up your id and determine your self as a registered consumer and then get further privileges.

This additionally applies whilst you log into on-line products and services the usage of your Facebook or Google accounts.

In this newsletter, we’re going to construct a Nodejs API with JWT (JSON Web Tokens) authentication. The equipment that we’re going to use in this educational are:

  • Expressjs
  • MongoDB database
  • Mongoose
  • Dotenv
  • Bcryptjs
  • Jsonwebtoken

Authentication Vs. Authorization

What is Authentication?

Authentication is the method of figuring out customers through obtaining credentials like electronic mail, password, and tokens. The given credentials are when compared to the registered consumer’s credentials, this is to be had in the report of the native laptop gadget or any databases. If the given credentials fit with the to be had information in the database, the authentication procedure is finished, and the consumer is authorized to get right of entry to the sources.

What is Authorization?

Authorization occurs after authentication. Every authorization will have to have an authentication procedure. It is the method of permitting customers to get right of entry to sources from the programs or a web site. In this educational, we can be authorizing logged-in consumer’s to get right of entry to the consumer’s information. If the consumer isn’t logged in, they gained’t be ready to use get right of entry to the knowledge.

The very best examples of authorization are social media platforms like Facebook and Twitter. You can’t get right of entry to social media content material with no need an account.

Another instance of authorization is subscription-based content material, your authentication can also be performed through login into the web site, however you gained’t be licensed to get right of entry to the content material till you haven’t subscribed.

Pre-requisite

Before you progress ahead, I guess you’ve got a fundamental working out of Javascript and MongoDB and excellent wisdom of Nodejs.

Make certain you’ve got put in node and npm in your native gadget. To take a look at if node and npm are put in in your laptop, open the command urged and sort node -v and npm -v. This will have to display the next end result.

Your variations would possibly fluctuate from mine. NPM robotically will get downloaded with the node. If you haven’t downloaded it but, obtain it from the NodeJS website.

You will want an IDE (Integrated construction setting) to write code. In this educational, I’m the usage of VS code editor. If you’ve got every other one, you’ll be able to use that too. If you don’t have any IDE put in in your laptop, you’ll be able to obtain it from the Visual Studio website. Download it according to your native gadget.

Project Set-up

Create a folder title nodeapi anyplace in your native laptop, and then open it with vs-code. Open the vs-code terminal and then initialize the node package deal supervisor through typing.

npm init -y

Make certain you’re at the nodeapi listing.

The above command will create a package deal.json report that holds all of the dependencies that we’re going to use in this undertaking.

Now we can obtain all of the programs discussed above, now sort and input them in the terminal.

npm set up categorical dotenv jsonwebtoken mongoose bcryptjs

Now, you’re going to have recordsdata and folders, as proven beneath.

Creating Server and Connecting Database

Now create a report named index.js and a folder named config. Inside config, create two recordsdata named conn.js to attach to the database and config.env to claim setting variables. Write the given code beneath in the respective recordsdata.

index.js

const categorical = require('categorical');
const dotenv = require('dotenv');

//Configure dotenv recordsdata above the usage of some other library and recordsdata
dotenv.config(trail:'./config/config.env'); 

//Creating an app from categorical
const app = categorical();

//Using categorical.json to get request of json information
app.use(categorical.json());



//listening to the server
app.concentrate(procedure.env.PORT,()=>
    console.log(`Server is listening at $procedure.env.PORT`);
)

If you’re the usage of dotenv, then config it in your index.js report ahead of calling every other recordsdata that makes use of setting variables.

conn.js

const mongoose = require('mongoose');

mongoose.attach(procedure.env.URI, 
     useNewUrlParser: true,
     useUnifiedTopology: true )
    .then((information) => 
        console.log(`Database attached to $information.connection.host`)
)

config.env

URI = 'mongodb+srv://ghulamrabbani883:[email protected]/?retryWrites=true&w=majority'
PORT = 5000

I’m the usage of mongo-DB Atlas URI, you’ll be able to use localhost as neatly.

Creating fashions and routes

Model is a format of your information in the Mongo-DB database and will likely be saved as a JSON record. To create a type, we’re going to use the mongoose schema.

Routing refers to how an utility responds to consumer requests. We will use the explicit router serve as to create routes.

Routing strategies typically take two arguments. The first is course, and the second one is the callback serve as to outline what this course would do on the consumer’s request.

It additionally takes a 3rd argument as a middleware serve as when wanted, like in the authentication procedure. As we’re development authenticated API, we can additionally use the middleware serve as to authorize and authenticate customers.

Now we can create two folders named routes and fashions. Inside routes, create a report title userRoute.js and within the fashions folder, create a report title consumerModel.js. After developing recordsdata, write the next code in the respective recordsdata.

consumerModel.js

const mongoose = require('mongoose');

//Creating Schema the usage of mongoose
const consumerSchema = new mongoose.Schema(
    title: 
        sort:String,
        required:true,
        minLength:[4,'Name should be minimum of 4 characters']
    ,
    electronic mail:
        sort:String,
        required:true,
        distinctive:true,
    ,
    password:
        sort:String,
        required:true,
        minLength:[8,'Password should be minimum of 8 characters']
    ,
    token:
        sort:String
    
)

//Creating fashions
const consumerModel = mongoose.type('consumer',consumerSchema);
module.exports = consumerModel;

userRoute.js

const categorical = require('categorical');
//Creating categorical router
const course = categorical.Router();
//Importing consumerModel
const consumerModel = require('../fashions/consumerModel');

//Creating sign in course
course.put up('/sign in',(req,res)=>

)
//Creating login routes
course.put up('/login',(req,res)=>

)

//Creating consumer routes to fetch customers information
course.get('/consumer',(req,res)=>

)

Implementing course capability and developing JWT tokens

What is JWT?

JSON internet tokens (JWT) is a javascript library that creates and check tokens. It is an open usual used to percentage knowledge between two events – a consumer and a server. We will use 3 purposes of JWT. The first one is, signal to create tokens, the second is genSalt to create salt, and the remaining serve as we’ve got is check to check the tokens.

What is bcryptjs?

Bcryptjs is a hashing serve as created through Niels Provos and David Mazières. It makes use of a hash set of rules to hash the password. It has two maximum not unusual purposes that we can be the usage of in this undertaking. The first bcryptjs serve as is hash to generate hash price and the second one serve as is evaluate serve as to evaluate passwords.

Implement course capability

The callback serve as in routing takes 3 arguments, request, reaction, and subsequent serve as. The subsequent argument is non-compulsory; move this best when you wish to have this. These arguments will have to be in the request, reaction, and subsequent order. Now adjust the userRoute.js, config.env, and index.js recordsdata with the next codes.

userRoute.js

//Requiring all of the essential recordsdata and libraries
const categorical = require('categorical');
const bcrypt = require('bcryptjs');
const jwt = require('jsonwebtoken');

//Creating categorical router
const course = categorical.Router();
//Importing consumerModel
const consumerModel = require('../fashions/consumerModel');

//Creating sign in course
course.put up("/sign in", async (req, res) => 

    attempt 
        const  title, electronic mail, password  = req.frame;
        //Check emptyness of the incoming information
        if (!title  catch (error) 
        go back res.json( error: error );
    

)
//Creating login routes
course.put up('/login', async (req, res) => 
    attempt  catch (error) 
        go back res.json( error: error );
    

)

//Creating consumer routes to fetch customers information
course.get('/consumer', async (req, res) => 
    attempt 
        const consumer  = anticipate consumerModel.in finding();
        if(!consumer)
            go back res.json(message:'No consumer discovered')
        
        go back res.json(consumer:consumer)
     catch (error) 
        go back res.json( error: error );  
    
)

module.exports = course;

If you’re the usage of Async serve as, use try-catch block, another way it is going to throw an unhandled promise rejection error.

config.env

URI = 'mongodb+srv://ghulamrabbani883:[email protected]/?retryWrites=true&w=majority'
PORT = 5000
SECRET_KEY = KGGK>HKHVHJVKBKJKJBKBKHKBMKHB
JWT_EXPIRE = 2nd

index.js

const categorical = require('categorical');
const dotenv = require('dotenv');

//Configure dotenv recordsdata above the usage of some other library and recordsdata
dotenv.config(trail:'./config/config.env'); 
require('./config/conn');
//Creating an app from categorical
const app = categorical();
const course = require('./routes/userRoute');

//Using categorical.json to get request of json information
app.use(categorical.json());
//Using routes

app.use('/api', course);

//listening to the server
app.concentrate(procedure.env.PORT,()=>
    console.log(`Server is listening at $procedure.env.PORT`);
)

Creating middleware to Authenticate consumer

What is middleware?

Middleware is a serve as that has get right of entry to to the request, reaction object, and subsequent serve as in the request-response cycle. The subsequent serve as is invoked when the serve as execution is finished. As I discussed above, use subsequent() in case you have to execute every other callback serve as or middleware serve as.

Now create a folder named middleware, and within it, create report title as auth.js and write the next code.

auth.js

const consumerModel = require('../fashions/consumerModel');
const jwt = require('jsonwebtoken');
const isAuthenticated = async (req,res,subsequent)=>
    attempt 
        const token = req.cookies;
        if(!token)
            go back subsequent('Please login to get right of entry to the knowledge');
        
        const check = anticipate jwt.check(token,procedure.env.SECRET_KEY);
        req.consumer = anticipate consumerModel.findById(check.identification);
        subsequent();
     catch (error) 
       go back subsequent(error); 
    


module.exports = isAuthenticated;

Now set up the cookie-parser library to configure the cookieParser in your app. cookieParser is helping you to get right of entry to the token saved in the cookie. If you don’t have cookieParser configured in your nodejs app, you gained’t be ready to get right of entry to the cookies from the headers of the request object. Now, write in the terminal to obtain cookie-parser.

npm i cookie-parser

Now, you’ve got a cookieParser put in. Configure your app through enhancing the index.js report and upload middleware to the “/consumer/” course.

index.js report

const cookieParser = require('cookie-parser');
const categorical = require('categorical');
const dotenv = require('dotenv');

//Configure dotenv recordsdata above the usage of some other library and recordsdata
dotenv.config(trail:'./config/config.env'); 
require('./config/conn');
//Creating an app from categorical
const app = categorical();
const course = require('./routes/userRoute');

//Using categorical.json to get request of json information
app.use(categorical.json());
//Configuring cookie-parser
app.use(cookieParser()); 

//Using routes
app.use('/api', course);

//listening to the server
app.concentrate(procedure.env.PORT,()=>
    console.log(`Server is listening at $procedure.env.PORT`);
)

userRoute.js

//Requiring all of the essential recordsdata and libraries
const categorical = require('categorical');
const bcrypt = require('bcryptjs');
const jwt = require('jsonwebtoken');
const isAuthenticated = require('../middleware/auth');

//Creating categorical router
const course = categorical.Router();
//Importing consumerModel
const consumerModel = require('../fashions/consumerModel');

//Creating consumer routes to fetch customers information
course.get('/consumer', isAuthenticated, async (req, res) => 
    attempt 
        const consumer = anticipate consumerModel.in finding();
        if (!consumer) 
            go back res.json( message: 'No consumer discovered' )
        
        go back res.json( consumer: consumer )
     catch (error) 
        go back res.json( error: error );
    
)

module.exports = course;

The “/consumer” course best be available when the consumer is logged in.

Checking the APIs on POSTMAN

Before you take a look at APIs, you wish to have to adjust the package deal.json report. Add the next traces of code.

"scripts": 
    "take a look at": "echo "Error: no take a look at specified" && go out 1",
    "get started": "node index.js",
    "dev": "nodemon index.js"
  ,

You can get started the server through typing npm get started, however it is going to best run as soon as. To stay your server working whilst converting recordsdata, you’re going to want nodemon. Download it through typing in the terminal

npm set up -g nodemon

-g flag will obtain the nodemon globally in your native gadget. You don’t have to obtain it once more and once more for each and every new initiatives.

To run the server, sort npm run dev in the terminal. You gets the next end result.

Finally, your code is finished, and the server is working as it should be, move to postman and take a look at whether it is running.

What is POSTMAN?

POSTMAN is a device device to design, construct, expand and take a look at API.

If you haven’t downloaded the postman in your laptop, obtain it from the postman website.

Now open the postman and create a suite title nodeAPItest, and within it, create 3 requests: sign in, login, and consumer. You will have to have the next recordsdata.

When you ship JSON information to the “localhost:5000/api/sign in” you’re going to get the next end result.

As we’re developing and saving tokens into cookies throughout sign in as neatly, you’ll be able to have the consumer element whilst you request the “localhost:5000/api/consumer” course. You can take a look at the remainder of the requests on POSTMAN.

If you need the the entire code you’ll be able to get it from my github account.

Conclusion

In this educational, we’ve got discovered how to practice authentication to the NodeJS API the usage of JWT tokens. We additionally licensed customers to get right of entry to the consumer information.

HAPPY CODING!

Related Articles

Leave a Reply

Your email address will not be published.

Back to top button