Securing Node.js Applications with JSON Web Tokens(JWT)
Tags: node, javascript, jwt, tokens
Published: 2020-06-05 23:28:41

Full article can be found <a href="https://taslangraham.com/2020/04/02/securing-node-js-applications-with-json-web-tokensjwt/" target="_blank">here</a>.
<!-- wp:paragraph {"backgroundColor":"modern-white","textColor":"modern-dark-gray"} -->
<p class="has-modern-dark-gray-color has-modern-white-background-color has-text-color has-background">Security is a critical component of most modern web applications. As you progress through your career, you will develop more and more applications which requires some level of security, namely <strong>authentication </strong>and <strong>authorization</strong>. One way to handle security in your application is through the use of JSON Web Tokens (JWT) which we'll discuss in this article.</p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p>First, there are some fundamental things that we need to cover before we start writing code. </p>
<!-- /wp:paragraph -->

<!-- wp:heading {"level":3} -->
<h3>What is Authentication?</h3>
<!-- /wp:heading -->

<!-- wp:image {"align":"center","id":411,"sizeSlug":"large"} -->
<div class="wp-block-image"><figure class="aligncenter size-large"><img src="https://taslangraham.files.wordpress.com/2020/04/log-in.jpg?w=1024" alt="" class="wp-image-411"/><figcaption>Image by <a href="https://pixabay.com/users/AchinVerma-387876/?utm_source=link-attribution&amp;utm_medium=referral&amp;utm_campaign=image&amp;utm_content=570317">Achin Verma</a> from <a href="https://pixabay.com/?utm_source=link-attribution&amp;utm_medium=referral&amp;utm_campaign=image&amp;utm_content=570317">Pixabay</a></figcaption></figure></div>
<!-- /wp:image -->

<!-- wp:paragraph -->
<p>In simple terms, authentication is verifying that a person or an entity is who it claims to be. A common way of authentication is combination of email/username with a password to log into web applications. After entering the combination of email/username with a password, the application checks to verify that this combination is correct, essentially authenticating the user. Access is granted <strong>only</strong> if the combination is correct.</p>
<!-- /wp:paragraph -->

<!-- wp:heading {"level":3} -->
<h3>What is Authorization?</h3>
<!-- /wp:heading -->

<!-- wp:image {"align":"center","id":412,"sizeSlug":"large"} -->
<div class="wp-block-image"><figure class="aligncenter size-large"><img src="https://taslangraham.files.wordpress.com/2020/04/auth.jpg?w=1024" alt="" class="wp-image-412"/></figure></div>
<!-- /wp:image -->

<!-- wp:paragraph -->
<p>Authorization determines the privileges or access levels that an authenticated user has on resources.  Resources includes computer programs, files, services, data and application features. </p>
<!-- /wp:paragraph -->

<!-- wp:heading {"level":3} -->
<h3>JSON Web Token</h3>
<!-- /wp:heading -->

<!-- wp:image {"align":"center","id":414,"sizeSlug":"large"} -->
<div class="wp-block-image"><figure class="aligncenter size-large"><img src="https://taslangraham.files.wordpress.com/2020/04/jwt_logo.jpg?w=1000" alt="" class="wp-image-414"/></figure></div>
<!-- /wp:image -->

<!-- wp:paragraph -->
<p><em>JSON Web Token (JWT) is an open standard (<a href="https://tools.ietf.org/html/rfc7519">RFC 7519</a>) that defines a compact and self-contained way for securely transmitting information between parties as a JSON object. This information can be verified and trusted because it is digitally signed. JWTs can be signed using a secret (with the&nbsp;<strong>HMAC</strong>&nbsp;algorithm) or a public/private key pair using&nbsp;<strong>RSA</strong>&nbsp;or&nbsp;<strong>ECDSA</strong>.</em> -<a rel="noreferrer noopener" aria-label=" (opens in a new tab)" href="https://jwt.io/introduction/" target="_blank">Jwt.io</a></p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p>What does this mean in simple terms? A JWT is an encoded string (token) which can be share between a server and client. The encoded string can hold data inside what is called a payload. <em>This information, though protected against tampering, is readable by anyone. Do not put secret information in the payload or header elements of a JWT unless it is encrypted</em>.</p>
<!-- /wp:paragraph -->

<!-- wp:heading {"level":3} -->
<h3>How JWT works in securing our application?</h3>
<!-- /wp:heading -->

<!-- wp:image {"align":"center","id":340,"sizeSlug":"large"} -->
<div class="wp-block-image"><figure class="aligncenter size-large"><img src="https://taslangraham.files.wordpress.com/2020/03/jwt-1.png?w=1024" alt="" class="wp-image-340"/></figure></div>
<!-- /wp:image -->

<!-- wp:heading {"level":3} -->
<h3>Project setup </h3>
<!-- /wp:heading -->

<!-- wp:image {"align":"center","id":416,"sizeSlug":"large"} -->
<div class="wp-block-image"><figure class="aligncenter size-large"><img src="https://taslangraham.files.wordpress.com/2020/04/setup.jpg?w=1024" alt="" class="wp-image-416"/><figcaption>Image by <a href="https://pixabay.com/users/qimono-1962238/?utm_source=link-attribution&amp;utm_medium=referral&amp;utm_campaign=image&amp;utm_content=2125183">Arek Socha</a> from <a href="https://pixabay.com/?utm_source=link-attribution&amp;utm_medium=referral&amp;utm_campaign=image&amp;utm_content=2125183">Pixabay</a></figcaption></figure></div>
<!-- /wp:image -->

<!-- wp:paragraph -->
<p>With all the background knowledge out of the way, it is time for the fun stuff! We are getting closer to writing some code, but first we have to set-up our project.</p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p>First, create a folder named <strong><em>node-jwt-example</em></strong>. Open your text editor of choice, I'm using VS Code, and open <strong><em>node-jwt-example</em></strong> folder.</p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p>We'll need to install a couple packages. Inside your project's root directory, open your terminal and run the following commands :</p>
<!-- /wp:paragraph -->

<!-- wp:list {"ordered":true} -->
<ol><li><strong>npm init</strong> - this will initialize your project and create a <em>package.json file.</em> Press enter and accept all the default settings.</li><li><strong>npm install express</strong> <strong>--save</strong> - express will handle all our routing</li><li><strong>npm install jsonwebtoken</strong> <strong>--save</strong> - install the JSON Web Token package for node</li><li><strong>npm install bcryptjs --save</strong> - will be used to hash our passwords</li><li><strong>npm install body-parser</strong> - parses incoming requests</li><li><strong>npm install mongoose</strong> - mongoose is used to interact with our MongoDb database</li><li><strong>npm install nodemon</strong> - automatically restarts server each time we save our changes</li></ol>
<!-- /wp:list -->

<!-- wp:heading {"level":4} -->
<h4>Now create the following folder structure</h4>
<!-- /wp:heading -->

<!-- wp:image {"align":"center","id":405,"sizeSlug":"large"} -->
<div class="wp-block-image"><figure class="aligncenter size-large"><img src="https://taslangraham.files.wordpress.com/2020/04/fld-str.png?w=291" alt="" class="wp-image-405"/></figure></div>
<!-- /wp:image -->

<!-- wp:heading -->
<h2>Lets Code! 👨🏾‍💻&nbsp;</h2>
<!-- /wp:heading -->

<!-- wp:paragraph -->
<p>Inside your <strong><em>app.js </em></strong>file, copy and paste the following code.</p>
<!-- /wp:paragraph -->

<!-- wp:group -->
<div class="wp-block-group"><div class="wp-block-group__inner-container"><!-- wp:code {"ampFitText":true} -->
<amp-fit-text layout="fixed-height" min-font-size="6" max-font-size="72" height="80"><pre class="wp-block-code"><code>const express = require('express');
const app = express();

const bodyParser = require("body-parser"); //use to parse incoming request bodies 
const db = require("./db");

app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());

const userRoutes = require('./routes/users');
app.use('/user', userRoutes); //tells express to forward user routes to routes/users.js

module.exports = app; // this should be the last line in your file
</code></pre></amp-fit-text>
<!-- /wp:code --></div></div>
<!-- /wp:group -->

<!-- wp:paragraph -->
<p>Here we are importing our express library. We've setup body-parser. We've also included our  <strong><em>users.js</em></strong> routes file which will handle all <strong><em>/user</em></strong> routes. We've also required in our <strong><em>db.js </em></strong>file which will hold the configuration for our database. Finally we've exported our <strong><em>app.js</em></strong> to make it accessible in other files.</p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p>Next, let us set up our server. Paste the following code inside your <strong><em>server.js </em></strong> file.</p>
<!-- /wp:paragraph -->

<!-- wp:code -->
<pre class="wp-block-code"><code>const http = require('http');
const app = require('./app');

const port = 5000; //selects process port or defaults it to 5000
const server = http.createServer(app);

server.listen(port, () => {
    console.log("listening on port " + port);
});</code></pre>
<!-- /wp:code -->

<!-- wp:paragraph -->
<p>Here we are setting up our server and assigning it a port number (5000).  The&nbsp;<strong>server</strong>.&nbsp;<strong>listen</strong>() method creates a listener on the specified port.  We then log a message to the console to signal that our server has been successfully set-up;</p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p>Next, we will add the basic set-up for our <strong><em>users.js </em></strong> file inside our <strong><em>routes folder.</em></strong></p>
<!-- /wp:paragraph -->

<!-- wp:code -->
<pre class="wp-block-code"><code>const express = require("express");
const router = express.Router();

const jwt = require('jsonwebtoken'); //use to create, verify, and decode tokens
const bcrypt = require('bcryptjs'); //use to hash passwords
const secret = require('../config').secret; //contains secret key used to sign tokens
const User = require("../models/User");

router.post("/register", (req, res) => {
})

router.post("/login", (req, res) => {
})

module.exports = router; //this should the last line of code</code></pre>
<!-- /wp:code -->

<!-- wp:paragraph -->
<p>Here we are setting up for two routes,  <strong><em>/register </em></strong>and <strong><em>/login</em></strong>. We then export our <strong><em>routes.js</em></strong> to make it accessible inside <strong><em>app.js</em></strong>.</p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p>Next, paste the following inside your <strong><em>config.js </em></strong>file.</p>
<!-- /wp:paragraph -->

<!-- wp:code -->
<pre class="wp-block-code"><code>module.exports = {
    dbUri: "mongodb://localhost/node-jwt",
    secret: "784sdsdsdhyohsd-098nwqjhu7324gcx64c847324gcx64cw5evr743c18448484809999999998",
}</code></pre>
<!-- /wp:code -->

<!-- wp:paragraph -->
<p>Notice the <strong><em>dbUri </em></strong>property inside our <strong><em>modules.exports </em></strong>object? This is the connection string that we will use later for our database.</p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p>Now we'll set-up our database connection. Paste the following code inside <strong><em>db.js</em></strong>.</p>
<!-- /wp:paragraph -->

<!-- wp:code -->
<pre class="wp-block-code"><code>const dbUri = require("./config").dbUri;
const mongoose = require('mongoose');
mongoose.connect(dbUri, { useNewUrlParser: true, useUnifiedTopology: true });</code></pre>
<!-- /wp:code -->

<!-- wp:paragraph -->
<p>Here we are retrieving the URI for our database from the <strong><em>config.js </em></strong>file.</p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p>We then require in mongoose (to interact with our database). Finally we connect to our database using the URI. </p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p>I am using a local connection for my mongoDb database. If you'd like to, you can create a live database <a href="https://www.mongodb.com/cloud/atlas/signup">here</a> and connect to that one.</p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p> Now we will build our User model. Add the following your <strong><em>User.js</em></strong> file inside the <strong>models</strong><em> </em>folder.</p>
<!-- /wp:paragraph -->

<!-- wp:code -->
<pre class="wp-block-code"><code>const mongoose = require('mongoose');

const UserSchema = new mongoose.Schema({
    email: String,
    password: String
});

mongoose.model('User', UserSchema);
module.exports = mongoose.model('User');</code></pre>
<!-- /wp:code -->

<!-- wp:paragraph -->
<p>We've created a simple schema. A schema defines the structure of the document. Each document inside our database collection will have an <strong><em>email </em></strong>and a <strong><em>password.</em></strong> We then use our schema to define a model, <strong><em>User</em></strong>. We will use the <strong><em>User</em></strong><em> </em>model to <strong><em>create, and retrieve Users</em></strong>.</p>
<!-- /wp:paragraph -->

<!-- wp:heading {"level":4} -->
<h4>Start server</h4>
<!-- /wp:heading -->

<!-- wp:paragraph -->
<p>Now let's start our server to ensure everything is working properly. </p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p>Add <strong><em><strong>"dev"</strong>:&nbsp;"nodemon&nbsp;server.js",</em></strong> to your <strong><em>package.json</em></strong> file.</p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p>Next, run the command <strong><em>npm run dev</em></strong> to start your server.</p>
<!-- /wp:paragraph -->

<!-- wp:image {"align":"center","id":408,"sizeSlug":"large"} -->
<div class="wp-block-image"><figure class="aligncenter size-large"><img src="https://taslangraham.files.wordpress.com/2020/04/npm-run-dev.png?w=499" alt="" class="wp-image-408"/></figure></div>
<!-- /wp:image -->

<!-- wp:paragraph -->
<p>You should see the message "listening on port 5000" printed to your terminal.</p>
<!-- /wp:paragraph -->

<!-- wp:heading {"level":4} -->
<h4>Register a User and create a token</h4>
<!-- /wp:heading -->

<!-- wp:paragraph -->
<p>We are now ready to start making using of JSON Web Tokens. We will register a User, create a token with the User ID as the payload, then we will return the token to our client. </p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p>I will be using <a rel="noreferrer noopener" href="https://www.postman.com/downloads/" target="_blank">Postman </a>to test my API endpoints.</p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p>Update your  <em><strong>/register </strong></em>endpoint in your <strong><em>user.js</em></strong> inside your <strong><em>routes </em></strong>folder to look like this.</p>
<!-- /wp:paragraph -->

<!-- wp:code -->
<pre class="wp-block-code"><code>router.post("/register", (req, res) => {
    const hashedPassword = bcrypt.hashSync(req.body.password, 10);

    User.create({
        email: req.body.email,
        password: hashedPassword,
    }).then((user) => {
        // create a token
        let token = jwt.sign({ id: user._id }, secret, {
            expiresIn: 86400 // expires in 24 hours
        })
        return res.status(201).send({ auth: true, token: token })
    })
        .catch((err) => {return res.send(err)})
})</code></pre>
<!-- /wp:code -->

<!-- wp:paragraph -->
<p>First we use  <strong><em>bcrypt</em></strong> to hash our password, because you should never save your passwords as plain text. We then create a User using the <strong>hashed password, and email</strong><em>. </em></p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p>We then create a token. The&nbsp;<code><strong>jwt.sign()</strong></code>&nbsp;method takes a payload and the <strong><em>secret</em></strong> key defined in&nbsp;<strong>config.js&nbsp;</strong>as parameters. It also takes another object which holds extra options. In this case the only option included is the <strong><em>expiresIn</em></strong> which tells the token to expire in 24 hours.  </p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p>The token will be a unique string of characters. A part of this string represents the payload.  In our case, the payload is an object containing only the id of the user.</p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p>If everything  was successful we return an object to the client which contains the token.</p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p><strong>Test our registration</strong></p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p>Inside postman, we will make a post request to <strong><em>http://localhost:5000/register</em></strong> with the user information to register a new user.</p>
<!-- /wp:paragraph -->

<!-- wp:image {"align":"center","id":363,"width":772,"height":386,"sizeSlug":"large"} -->
<div class="wp-block-image"><figure class="aligncenter size-large is-resized"><img src="https://taslangraham.files.wordpress.com/2020/03/reg1.png?w=1024" alt="" class="wp-image-363" width="772" height="386"/></figure></div>
<!-- /wp:image -->

<!-- wp:paragraph -->
<p>Ensure that the HTTP method is set to POST. Click <strong>body</strong>, then select the<strong><em> x-www-form-urlencoded</em></strong>, next add the email and password as key-pair values. Click <strong><em>Send</em></strong>. You should recieve the following response.</p>
<!-- /wp:paragraph -->

<!-- wp:image {"align":"center","id":372,"width":770,"height":353,"sizeSlug":"large"} -->
<div class="wp-block-image"><figure class="aligncenter size-large is-resized"><img src="https://taslangraham.files.wordpress.com/2020/03/reg2.png?w=1024" alt="" class="wp-image-372" width="770" height="353"/></figure></div>
<!-- /wp:image -->

<!-- wp:paragraph -->
<p>Awesome! Our registration is working. We are receiving our token. We will use this token in subsequent requests. We can also use this token retrieve user information. Let's do that.</p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p>Add the following code to your <strong><em>user.js </em></strong>file inside your <strong><em>routes </em></strong>folder.</p>
<!-- /wp:paragraph -->

<!-- wp:code -->
<pre class="wp-block-code"><code>router.get('/current-user', function (req, res, next) {
    const authHeader = req.headers&#91;'authorization'];
    const token = authHeader &amp;&amp; authHeader.split(' ')&#91;1];

    if (!token)
        return res.status(403).send({ auth: false, msg: 'No token provided.' });

    jwt.verify(token, secret, function (err, decoded) {
        if (err)
            return res.status(500).send({ auth: false, msg: 'Failed to authenticate token.' });

        User.findById(decoded.id, { password: 0 }, function (err, user) {
            if (err) return res.status(500).send("There was a problem finding the user.");
            if (!user) return res.status(404).send("No user found.");

            return res.status(200).send(user);
        });
    });
});</code></pre>
<!-- /wp:code -->

<!-- wp:paragraph -->
<p>First we extract the token sent by the client.  If there's no token, we return an appropriate message, and set auth to false. </p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p>If there's a token we verify it using the <strong><em>jwt.verify()</em></strong> method.  We pass three parameters to this method, the <strong><em>token</em></strong> we want to verify, the <em><strong>secret key</strong></em> used to sign our tokens, and a callback function where we will handle the decoded token returned by <strong><em>jwt.verify()</em></strong>. We then use the decoded <strong><em>id </em></strong>to find our User inside our database using the  <strong><em>User.findById() </em></strong>method. The <strong><em>{ password: 0 }</em></strong>  parameter signals the <strong><em>User.findById()</em></strong> to not return the password field.  We then return the User to our client. We also handled any errors that may have occurred. Let us test this in postman.</p>
<!-- /wp:paragraph -->

<!-- wp:image {"align":"center","id":377,"sizeSlug":"large"} -->
<div class="wp-block-image"><figure class="aligncenter size-large"><img src="https://taslangraham.files.wordpress.com/2020/04/reg3.png?w=1024" alt="" class="wp-image-377"/></figure></div>
<!-- /wp:image -->

<!-- wp:paragraph -->
<p>Inside postman enter this url <strong><em>http://localhost:5000/user/current-user</em></strong>. Ensure that postman is set to GET. Next we must add the token to our request header. Click the <strong><em>Headers</em></strong> tab, enter <strong><em>Authorization</em></strong><em> </em><strong> </strong>as a <strong><em>key, </em></strong>then inside the <strong><em>Value </em></strong>field, type <em><strong>Bearer followed by your token (e.g Bearer token_goes_here). </strong></em>Press <strong><em>Send</em></strong>. If all went well, an object containing our user should be returned, else you'll receive one of the error responses. </p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p><strong>We have completed registration and can use our token to get user details</strong>.</p>
<!-- /wp:paragraph -->

<!-- wp:heading {"level":4} -->
<h4>No we will implement login functionality for existing users.</h4>
<!-- /wp:heading -->

<!-- wp:paragraph -->
<p>We must have a way for existing users to log into our application. The login functionality is quite simple. Update your  <strong><em>/login</em></strong> inside your <strong><em>user.js </em></strong>file, inside your <em><strong>routes folder</strong> </em>to look like the following.</p>
<!-- /wp:paragraph -->

<!-- wp:code -->
<pre class="wp-block-code"><code>router.post('/login', function (req, res) {

    User.findOne({ email: req.body.email }, function (err, user) {
        if (err) return res.status(500).send('Error on the server.');
        if (!user) return res.status(404).send('Invalid Credentials');

        const passwordIsValid = bcrypt.compareSync(req.body.password, user.password);
        if (!passwordIsValid) return res.status(401).send({ auth: false, token: null, msg: 'Invalid Credentials' });

        const token = jwt.sign({ id: user._id }, secret, {
            expiresIn: 86400 // expires in 24 hours
        });

        res.status(200).send({ auth: true, token: token });
    });
});</code></pre>
<!-- /wp:code -->

<!-- wp:paragraph -->
<p>First we check for a user, using the <strong><em>User.findOne()</em></strong> method, who's email matches the one submitted. If we found a user, we then compare the hash value of the submitted password, using the <strong><em>bcrypt.compareSync(),</em></strong> with the hashed password for the User found. If this password does not match then we send an appropriate response indication that invalid credentials were used, set auth to <strong><em>false, </em></strong>and set token to <strong><em>null</em></strong>. If the passwords match, we sign a new token, attach the User ID as a payload and return this token to the client, with auth set to <strong><em>true</em></strong>.</p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p>Let's test it in postman</p>
<!-- /wp:paragraph -->

<!-- wp:image {"align":"center","id":383,"sizeSlug":"large"} -->
<div class="wp-block-image"><figure class="aligncenter size-large"><img src="https://taslangraham.files.wordpress.com/2020/04/log1.png?w=1024" alt="" class="wp-image-383"/><figcaption>Login with correct credentials</figcaption></figure></div>
<!-- /wp:image -->

<!-- wp:paragraph -->
<p>Awesome! It works as expected. Now what will happen if we submit an incorrect password?</p>
<!-- /wp:paragraph -->

<!-- wp:image {"align":"center","id":384,"sizeSlug":"large"} -->
<div class="wp-block-image"><figure class="aligncenter size-large"><img src="https://taslangraham.files.wordpress.com/2020/04/log2.png?w=1024" alt="" class="wp-image-384"/><figcaption>attempt to login with incorrect credentials</figcaption></figure></div>
<!-- /wp:image -->

<!-- wp:heading -->
<h2>Authorization</h2>
<!-- /wp:heading -->

<!-- wp:paragraph -->
<p>With authentication out of the way, we can now focus on authorization. Our authorization mechanism will be very simple.</p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p>We will create an endpoint <strong><em>/user/get-quote </em></strong>and we will ensure that only a user with a specific email can make a request to this endpoint and receive a quote. Paste the following inside your <strong><em>user.js </em></strong>route.</p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p><strong>Note: you would not have such simple authorization in a real world application. </strong></p>
<!-- /wp:paragraph -->

<!-- wp:code -->
<pre class="wp-block-code"><code>router.get("/get-quote", (req, res) => {
    const quote = "If a thing is humanly possible, consider it within your reach. - Marcus Aurelius";
    const acceptedEmail = "taslan@taslangraham.com.com"; //replace with email you registered with

    const authHeader = req.headers&#91;'authorization'];
    const token = authHeader &amp;&amp; authHeader.split(' ')&#91;1];

    if (!token)
        return res.status(403).send({ auth: false, msg: 'No token provided.' });


    jwt.verify(token, secret, function (err, decoded) {
        if (err)
            return res.status(500).send({ auth: false, message: 'Failed to authenticate token.' });

        User.findById(decoded.id, { password: 0 }, function (err, user) {
            if (err) return res.status(500).send("There was a problem.");

            if (!user) return res.status(404).send("You must have an account to make this request.");
            if (user.email !== acceptedEmail) return res.status(401).send("You are not authorized.");

            return res.status(200).send(quote);
        });
    });
})</code></pre>
<!-- /wp:code -->

<!-- wp:paragraph -->
<p>Here we verified and decoded a token. We then find a user using the <strong><em>id </em></strong>on the decoded token. We then check if this user's email is the same as our accepted email (acceptedEmail), then return the quote to the user.</p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p>Test it in postman.</p>
<!-- /wp:paragraph -->

<!-- wp:image {"align":"center","id":388,"sizeSlug":"large"} -->
<div class="wp-block-image"><figure class="aligncenter size-large"><img src="https://taslangraham.files.wordpress.com/2020/04/quote-1.png?w=1024" alt="" class="wp-image-388"/></figure></div>
<!-- /wp:image -->

<!-- wp:paragraph -->
<p>What if we use a token for a different user?</p>
<!-- /wp:paragraph -->

<!-- wp:image {"align":"center","id":391,"sizeSlug":"large"} -->
<div class="wp-block-image"><figure class="aligncenter size-large"><img src="https://taslangraham.files.wordpress.com/2020/04/quote-2.png?w=1024" alt="" class="wp-image-391"/></figure></div>
<!-- /wp:image -->

<!-- wp:heading {"level":4} -->
<h4>Middlewares</h4>
<!-- /wp:heading -->

<!-- wp:paragraph -->
<p>Notice that the logic used to verify a token is the same as the logic inside the  <strong><em>/current-user</em></strong> route handler? We can place this logic into what is known as a middleware.</p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p> Then we can use this middleware on any route that we wish to verify a token. </p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p>We can also place the logic to check if a user is authorized inside of a middleware as well. </p>
<!-- /wp:paragraph -->

<!-- wp:heading {"level":4} -->
<h4>First, what is a middleware</h4>
<!-- /wp:heading -->

<!-- wp:paragraph -->
<p><em>Middleware</em>&nbsp;functions are functions that have access to the&nbsp;<a href="https://expressjs.com/en/4x/api.html#req">request object</a>&nbsp;(<code>req</code>), the&nbsp;<a href="https://expressjs.com/en/4x/api.html#res">response object</a>&nbsp;(<code>res</code>), and the&nbsp;<code>next</code>&nbsp;function in the application’s request-response cycle. The&nbsp;<code>next</code>&nbsp;function is a function in the Express router which, when invoked, executes the middleware succeeding the current middleware.</p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p>Middleware functions can perform the following tasks:</p>
<!-- /wp:paragraph -->

<!-- wp:list -->
<ul><li>Execute any code.</li><li>Make changes to the request and the response objects.</li><li>End the request-response cycle.</li><li>Call the next middleware in the stack.</li></ul>
<!-- /wp:list -->

<!-- wp:paragraph -->
<p>If the current middleware function does not end the request-response cycle, it must call&nbsp;<code>next()</code>&nbsp;to pass control to the next middleware function. Otherwise, the request will be left hanging. </p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p>Paste the following code inside <strong><em>verifyToken.js</em></strong> in your middlewares folder.</p>
<!-- /wp:paragraph -->

<!-- wp:code -->
<pre class="wp-block-code"><code>const jwt = require('jsonwebtoken');
const secret = require('../config').secret;

const verifyToken = (req, res, next) => {
    const authHeader = req.headers&#91;'authorization'];
    const token = authHeader &amp;&amp; authHeader.split(' ')&#91;1];

    if (!token)
        return res.status(403).send({ auth: false, message: 'No token provided.' });

    jwt.verify(token, secret, function (err, decoded) {
        if (err)
            return res.status(500).send({ auth: false, message: 'Failed to authenticate token.' });

        req.userId = decoded.id;
        next();
    });
}
module.exports = verifyToken;</code></pre>
<!-- /wp:code -->

<!-- wp:paragraph -->
<p>Add this line of code to the top of your <strong><em>user.js </em></strong>route file</p>
<!-- /wp:paragraph -->

<!-- wp:code -->
<pre class="wp-block-code"><code>const verifyToken = require("../middlewares/verifyToken");</code></pre>
<!-- /wp:code -->

<!-- wp:paragraph -->
<p>Change your <strong><em>/current-user</em></strong> endpoint to the following.</p>
<!-- /wp:paragraph -->

<!-- wp:code -->
<pre class="wp-block-code"><code>router.get('/current-user', verifyToken, function (req, res, next) {
    User.findById(req.userId, { password: 0 }, function (err, user) {
        if (err) return res.status(500).send("There was a problem finding the user.");
        if (!user) return res.status(404).send("No user found.");

        res.status(200).send(user);
    });
});</code></pre>
<!-- /wp:code -->

<!-- wp:paragraph -->
<p>Notice we used our <strong><em>verifyToken</em></strong> middleware. Also, our code is much simpler now.</p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p>Now test the <strong><em>/current-user</em></strong> route inside postman.</p>
<!-- /wp:paragraph -->

<!-- wp:image {"align":"center","id":394,"sizeSlug":"large"} -->
<div class="wp-block-image"><figure class="aligncenter size-large"><img src="https://taslangraham.files.wordpress.com/2020/04/middleware1.png?w=1024" alt="" class="wp-image-394"/><figcaption>It still works</figcaption></figure></div>
<!-- /wp:image -->

<!-- wp:paragraph -->
<p>Now we will create our <strong>isAuthorized </strong>middleware. Paste the following inside your <strong>isAuthorized<em>.js</em></strong> file.</p>
<!-- /wp:paragraph -->

<!-- wp:code -->
<pre class="wp-block-code"><code>const User = require("../models/User");

const isAuthorized = (req, res, next) => {
    const acceptedEmail = "taslan@taslangraham.com";

    User.findById(req.userId, { password: 0 }, function (err, user) {
        if (err) return res.status(500).send("There was a problem.");

        if (!user) return res.status(404).send("You must have an account to make this request.");
        if (user.email !== acceptedEmail) return res.status(401).send("You are not authorized.");
        req.email = user.email;
        next();
    });
}

module.exports = isAuthorized;</code></pre>
<!-- /wp:code -->

<!-- wp:paragraph -->
<p>Now add this line of code at the top of your <strong><em>user.js</em></strong> route file.</p>
<!-- /wp:paragraph -->

<!-- wp:code -->
<pre class="wp-block-code"><code>const isAuthorized = require("../middlewares/isAuthorized");
</code></pre>
<!-- /wp:code -->

<!-- wp:paragraph -->
<p>We can now use the <strong>isAuthorized</strong> middleware.  Change your <strong><em>/get-quote</em></strong> endpoint to look like this. </p>
<!-- /wp:paragraph -->

<!-- wp:code -->
<pre class="wp-block-code"><code>router.get("/get-quote", verifyToken, isAuthorized, (req, res) => {
    const quote = "If a thing is humanly possible, consider it within your reach. - Marcus Aurelius";
    return res.status(200).send(quote);
})</code></pre>
<!-- /wp:code -->

<!-- wp:paragraph -->
<p>Notice we added both middlewares (<em><strong>verifyToken, and  isAuthorized</strong></em>). You can combine middlewares. All our logic is now inside the <em><strong>isAuthorized</strong></em> middleware, making our code much cleaner. We can now test this in postman.</p>
<!-- /wp:paragraph -->

<!-- wp:image {"align":"center","id":399,"sizeSlug":"large"} -->
<div class="wp-block-image"><figure class="aligncenter size-large"><img src="https://taslangraham.files.wordpress.com/2020/04/quote3.png?w=1024" alt="" class="wp-image-399"/><figcaption>works perfectly</figcaption></figure></div>
<!-- /wp:image -->

<!-- wp:heading {"level":3} -->
<h3>Recap</h3>
<!-- /wp:heading -->

<!-- wp:paragraph -->
<p>we've successfully implemented authentication, and authorization in our node.js application using JSON Web Tokens (JWT). We've also created middlewares to execute on our application’s request-response cycle. </p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p>Thank you for reading. If you caught an error, please let me know in the comments. Until next time, <em>think, learn, create, repeat!</em></p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p></p>
<!-- /wp:paragraph -->

<!-- wp:heading {"level":4} -->
<h4>Sources</h4>
<!-- /wp:heading -->

<!-- wp:paragraph -->
<p>https://searchsecurity.techtarget.com/definition/authentication</p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p>https://techterms.com/definition/authentication</p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p>https://www.techopedia.com/definition/10237/authorization</p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p>https://jwt.io/introduction/</p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p>https://www.tutorialspoint.com/expressjs/expressjs_routing.htm</p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p>https://www.tutorialspoint.com/expressjs/expressjs_routing.htm</p>
<!-- /wp:paragraph -->
<a href="https://www.buymeacoffee.com/taslan" target="_blank"><img src="https://cdn.buymeacoffee.com/buttons/default-orange.png" alt="Buy Me A Coffee" style="height: 51px !important;width: 217px !important;" ></a>