<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Narendra Maurya on Medium]]></title>
        <description><![CDATA[Stories by Narendra Maurya on Medium]]></description>
        <link>https://medium.com/@mauryavanshinarendra?source=rss-d3e8a6ddb3e3------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*Jt0cq_VLfroQnq7UBQYxzw.jpeg</url>
            <title>Stories by Narendra Maurya on Medium</title>
            <link>https://medium.com/@mauryavanshinarendra?source=rss-d3e8a6ddb3e3------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Fri, 27 Nov 2026 23:39:03 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@mauryavanshinarendra/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[JWT Authentication and Authorization middleware with Passport and Node Express and MongoDB.]]></title>
            <link>https://mauryavanshinarendra.medium.com/jwt-authentication-and-authorization-middleware-with-passport-and-node-express-and-mongodb-4c7fa839310c?source=rss-d3e8a6ddb3e3------2</link>
            <guid isPermaLink="false">https://medium.com/p/4c7fa839310c</guid>
            <category><![CDATA[authorization]]></category>
            <category><![CDATA[nodejs]]></category>
            <category><![CDATA[expressjs]]></category>
            <category><![CDATA[rest-api]]></category>
            <category><![CDATA[authentication]]></category>
            <dc:creator><![CDATA[Narendra Maurya]]></dc:creator>
            <pubDate>Sat, 06 Feb 2021 19:16:13 GMT</pubDate>
            <atom:updated>2021-02-09T01:54:12.928Z</atom:updated>
            <content:encoded><![CDATA[<h3>JWT Authentication and Authorization middleware in Node Express and MongoDB.</h3><p>It took me a long time to create a middleware with which we can protect API routes based on the user’s role. After going through the basics of the node express application and using custom middlewares for express application. I was successfully able to create something like this. If you want to learn this whole process of creating role checker middleware in Node Express. Follow this tutorial published by <a href="https://github.com/nandymandy1">Narendra Maurya</a> (Me) on my YouTube Channel. <a href="https://www.youtube.com/channel/UC7fpWskUFi90sANs9QXRVsg">Codebook Inc.</a></p><p>Role-based API authentication and Authorization using Passport and Custom Role Checker Middleware with JSON web tokens. For a complete YouTube, playlist <a href="https://www.youtube.com/watch?v=QbgJgZY7vBM&amp;list=PLpGo-Y3em4SVwae7sxS5kaZm8RitFF1js&amp;ab_channel=CodebookInc.">click here</a>.</p><p>For the Github repository <a href="https://github.com/nandymandy1/Role_based_api">click here</a>, which I will be soon updating with es6 modules and codes.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-Jq6Xv5YwNSrS26Qh2DZ9Q.jpeg" /><figcaption>YouTube Thumbnail</figcaption></figure><p>So now let’s start learning by coding it step by step by create a Simple Node Express Application.</p><pre>$ mkdir auth-role-api &amp;&amp; cd auth-role-api<br>$ npm init -y</pre><p>With this, we will be able to create a barebones Node.Js application. and then we will add dependencies to our application. And then I will explain what role each package will play in our application.</p><pre>$ npm i express mongoose passport passport-jwt jsonwebtoken consola bcryptjs cors body-parser dotenv</pre><pre>$ npm i -D nodemon</pre><h3>Packages</h3><ul><li>Express: This package will be used to spin up a simple node server using the express.js framework which is a barebones framework and we can do a lot of magic with that.</li><li>Mongoose: This package will be used in order to connect with the MongoDB database which is a NoSQL database. And comes up with added benefits like using ORM’s and creating MongoDB models and executing queries.</li><li>Passport and Passport-JWT: We will be using this package in order to create our own login strategy to authenticate our user based on the Login (Authentication Bearer) token which will be passed in the headers of the API request. We will be using this in our express application by injecting it as a middleware.</li><li>JSON webtokens: With the help of the package we will be issuing our authentication token and sending it back to the user after successful authentication.</li><li>BCRYPT.JS: This is package will be helpful in hashing and comparing our user’s passwords so that they are not saved in plain strings.</li><li>CORS: Since this whole application will be accessed by some kind of frontend frameworks like Vue.js or Angular or React (etc). There will be so many cross-origin API requests and by default express framework will block them by cors policy. This application will be enabling all the requests, you can even pass arguments to allow certain origins to access our express resources. In this demonstration, we will allow all origins.</li><li>Consola: It&#39;s a very simple but useful package by NUXT.js team and helps in giving nice console statements. This is just an add-on for fancy console statements 😉.</li><li>Body-parser: Since we will be exchanging a lot of JSON data from the Client to the server so we need to use some kind of middleware to handle JSON data. Instead of writing custom code for that and wasting time, we can make the use of body-parser package, and now it&#39;s also inbuilt in express.js, all you need is to <a href="https://medium.com/@mmajdanski/express-body-parser-and-why-may-not-need-it-335803cd048c">configure it</a>. (Article is mentioned over here.)</li><li>Dotenv: To pull in application environment variables and use them in our express application.</li></ul><p>Now we will be focusing on creating a proper folder structure with clean-code, which will make our code look cleaner and modular.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/914/1*1DyhKvthJBwlrsomvRWBxw.png" /></figure><p>Now firstly we will create the entry point of the application which in this screenshot is app.js but we will create index.js, and then we will add the start script in the package.json file, in the scripts object. And also we are using nodemon as a development dependency which will keep an eye on the server file and restart after noticing any change in the files.</p><pre>&quot;scripts&quot; : {<br>    &quot;start&quot; : &quot;node index.js&quot;,<br>    &quot;dev&quot; : &quot;nodemon index.js&quot;<br>},</pre><h3>Application Constants</h3><p>Let’s start by creating a .env file in the root of the application which will hold application constants.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/1143d83689d010063eb28a8dbef34fdc/href">https://medium.com/media/1143d83689d010063eb28a8dbef34fdc/href</a></iframe><p>Here we have defined 3 application constants</p><ul><li><strong>APP_SECRET</strong> for hashing our JWT token</li><li><strong>APP_PORT </strong>for the application port</li><li><strong>APP_DB </strong>for the database connection string</li></ul><p>Here in the database, I’m using the local database which is running in my docker container with a mongo image. Here you can use mongodb atlas cluster instead of it.</p><p>Now let us pull our environment variables into our application using the dotenv package. So we will create an index.js file in our config folder and will bring in dotenv package and instantiate config function from that which will get all the environment variables into our application. So here we have exported a default object which contains all of our constants.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/5d91750c6e2d082fa5dcdedd8078a0af/href">https://medium.com/media/5d91750c6e2d082fa5dcdedd8078a0af/href</a></iframe><p>Notice here in PORT we have used process.env.PORT || process.env.APP_PORT, which means that if the application is in production mode and PORT of the hosting server is defined then it uses that port to host our application otherwise it will fall back to what we have defined in our .env file.</p><h3>Entry Point</h3><p>So in the root of the application now we will create our simple express server by creating an index.js file in the root of the application and add body-parser and cors middlewares and also connect with our MongoDB database by pulling in the constants which were exported from the config folder.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/0671793bb2e8ddcb6e1cc8ce017ba668/href">https://medium.com/media/0671793bb2e8ddcb6e1cc8ce017ba668/href</a></iframe><p><strong>Model</strong></p><p>Now we will start working on our User Model. So for that, we will get into the models&#39; directory and create a new file named User.js, which will be exporting our User model. We will create a simplified user model.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/7ed0872bf3a7c634d14c3d4f12d0f8d6/href">https://medium.com/media/7ed0872bf3a7c634d14c3d4f12d0f8d6/href</a></iframe><p>Firstly we have brought in the Schema and model from the mongoose package to work with. Our user model contains basic user information like name, email, username, password, and as you can see there is a role field that is of type String and uses enum of roles as strings [“user”, “admin”, “superadmin”]. So for this application, we will be dealing with 3 types of users. And also you can see we have enabled timestamps to true, which will provide createdAt and updatedAt fields to our user model. And at last, we have exported mongoose model which refers to the “users” collection in the Database and uses the above-defined User Schema.</p><p><strong>API Routes or Endpoints</strong></p><p>So now it&#39;s time to go ahead and start defining our API routes for the application which will be dealing with our user functions like Registration (SignUp), Authentication (Login), and Get the user’s profile. We will start by creating a file called users.js in the routes directory and then import the Router function from the express package and instantiate it and then export it as default from this file. But for the registration and login, we are going to create 3 separate routes for each process, which are listed as follows:</p><p><strong>Registration Routes</strong></p><ul><li>One for registering the super-admin.</li></ul><pre>api/users/register-super-admin</pre><ul><li>Another for registering the admin.</li></ul><pre>api/users/register-admin</pre><ul><li>Third one for registering the user.</li></ul><pre>api/users/register-user</pre><p><strong>Authentication (Login) Routes</strong></p><ul><li>Authenticate General User</li></ul><pre>api/users/login-user</pre><ul><li>Authenticate Admin</li></ul><pre>api/users/login-admin</pre><ul><li>Authenticate Super Admin</li></ul><pre>api/users/login-super-admin</pre><p>And at last but not least, we are going to define the API end point which will return the Authenticated user’s profile.</p><pre>api/users/my-profile</pre><p>Now we will start adding the functionality of registering, authenticating the user, and bind them with the above-defined APIs.</p><p>So now in the utils directory, we will create a new file named userFunctions.js and in that file, we will bring in our User model from the model’s directory.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/083bf1277ebed6471cd068cd16f5f56f/href">https://medium.com/media/083bf1277ebed6471cd068cd16f5f56f/href</a></iframe><p>You can also see that we have created named functions which are as follows:</p><ul><li><strong>serializeUser:</strong> This is will remove extra protected fields from the user object which shouldn’t be exposed like password fields.</li><li><strong>validateEmail: </strong>This is function will check if the email entered for the registration is unique or not.</li></ul><p>Updating Soon till then you can follow my youtube tutorial. And subscribe to our channel to help us and motivate us to come up with more advanced concepts in NODE Express and MongoDB.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4c7fa839310c" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>