Consuming JWT API with MongoDB and Node.js part-3# Verify Token, Decode Token , Route Protection

View this thread on: d.buzz | hive.blog | peakd.com | ecency.com
·@alfarisi94·
0.000 HBD
Consuming JWT API with MongoDB and Node.js part-3# Verify Token, Decode Token , Route Protection
#### What Will I Learn?

- Verify Token
- Decode token
- A protected route with token
- Checking the user who is logged in

#### Requirements
Write here a bullet list of the requirements for the user in order to follow this tutorial.

-  node.js
- Install Express.js
- Install Postman
- Basic node.js, javascript es6
- Watch [part1](https://utopian.io/utopian-io/@alfarisi94/consuming-jwt-api-with-mongodb-and-node-js-part-1-setup-jwt-setup-database-create-router-api), [part2](https://utopian.io/utopian-io/@alfarisi94/consuming-jwt-api-with-mongodb-and-node-js-part-2-validate-user-create-token)

#### Difficulty
- Intermediate

### Protection on route
In the previous tutorial [Consuming JWT API with MongoDB and Node.js part-2# User Validation, Create token.](https://utopian.io/utopian-io/@alfarisi94/consuming-jwt-api-with-mongodb-and-node-js-part-2-validate-user-create-token). We have created the validation and successfully created the token. now we will use the token to protect the route. So later all routing that we protect will check token from a user.

***Noted***:  We must make the route protection function on the route to be protected.

- **Create a protection function**

We can use the **use ()** method to create a protection function. as usual, the method use () has 2 parameters. as usual, the method use () has 2 functions. They are **(req, res)**. but I added 1 additional parameter that is next. next is useful for making the decision to continue or cancel access to the route. but I added **1**additional parameter that is **next**. next is useful for making the decision to continue or cancel access to the route.

**Example:**
<pre>
<code>
router.use(function(req, res, next){
	//get token
		var token = req.body.token || req.query.token || req.headers['authorization'];
	//decode token
	if(token){
		jwt.verify(token, app.get('secretKey'), function(err, decode){
			if(err){
				return res.json({
					success: false,
					message: 'There was a problem during verification'
				})
			}else{
				req.decode =  decode
				next();
			}
		})
	}else{
		return res.status(403).send({
			status:false,
			message: 'Token not available '
		});
	}
})
</code>
</pre>

- **Get Token**

We can retrieve the user token. there are several ways to retrieve user tokens. 
- <code>req.body.token</code> :  With <code>req</code> , We can get token in body and with **token: valueOfToken**.
![Screenshot_26.png](https://cdn.utopian.io/posts/8d0f6fc87459ff3e92743f1c4a47aa60b852Screenshot_26.png)

- <code>req.query.token</code> : With  <code>req</code> , We can get token from query parameter and with **token='token'**.

![Screenshot_27.png](https://cdn.utopian.io/posts/f54ad58abdcfddb2937eab4faf47282b3b45Screenshot_27.png)

- <code>req.headers['authorization']</code>: With <code>req</code> , We can get token by headers['authorization']  in headers with key **'authorization'**.

![Screenshot_28.png](https://cdn.utopian.io/posts/280b754eb3e41754b9b2d456bc38cfb62479Screenshot_28.png)

and we can create an ***if {} else {}*** to check whether token exists or does not exist.
<pre>
<code>
if(token){
// do something if token available 
	}else{
		return res.status(403).send({
			status:false,
			message: 'Token not available '
		});
	}
</code>
</pre>

If the token is not available we can make a response with the**status (403)**., and give the message <code>message: 'Token not available '</code>
- **Decode Token**

The generated token contain encrypted data, and to know the encrypted data in the token. We have to *decode* the token by using the **verify ()** method of **JWT.**

**Example:**

<pre>
<code>
jwt.verify(token, app.get('secretKey'), function(err, decode){
			if(err){
				return res.json({
					success: false,
					message: 'There was a problem during verification'
				})
			}else{
				req.decode =  decode
				next();
			}
		})
</code>
</pre>

method verify () has 3 mandatory parameters to decode token. They are :

**1.  token**: The first parameter is the token to be decoded.

**2.  secret key:** The second parameter is the secret key that we use when we will generate the token. in this tutorial, we can get it in the <code>app.get ('secretKey')</code>.

**3.  function(err, decode):** The third parameter is an anonymous function that has two callback parameters. They are **error(err)** and **decode(decode)**. in this tutorial the parameters are <code>(err, decode)</code>.
We can check if there is an error **if (err)** and give response in **JSON** <code>return res.json({success: false, message: 'There was a problem during verification'})</code>

- *req.decode =  decode*: We can save the decode results in <code>req.decoded</code>, and to proceed into the destination route after verification, we add the next **method ().**
<br>
<br>
<br>
- **Check expired token**

We can check the expiration period of the token in this way:

**Example:**
<pre>
<code>
if(decode.exp <= Date.now()/1000){
	return res.status(400).send({
			status:false,
			message: 'Token has expired'
			})
	}
</code>
</pre>

We can check by using if (), then add the mathematical operator **<=**. 
- *decode.exp* : **decode** is the decode of the **verify()** function which we have described above, and **exp** is the expression value in units of a second.
- *Date.now()/1000* :  This is the method in javascript to get the time. but because of **decode.exp** in a second unit. then we have to change **Date.now()** into second unit with **/ 1000**.
Then we can respond in JSON with **status (400)**. <code>return res.status(400).send({status:false,message: 'Token has expired'})</code>

- **Checking the user who is logged in**

to see the currently logged in user, we need to create a new routing. I will create a new routing that is <code>'/ profile'</code>.

**Example:**
<pre>
<code>
router.get('/profile', function(req, res){
	res.json(req.decode._doc);
});
</code>
</pre>

We have stored the **decoded** token into **req.decode** <code>(req.decode = decode)</code>. There will be a lot of data stored in **req.decode**.  to specify just take the data only, we can use <code>._doc</code>.

### Result
We can see the result by running postman, we will see the user data being logged using routing '**/ profile'**.

![Screenshot_30.png](https://cdn.utopian.io/posts/96801dd74cc9cde1e1f5f0b9d6391ba36524Screenshot_30.png)

- **FULL CODE**
<pre>
<code>
router.use(function(req, res, next){
	//get token
	var token = req.body.token || req.query.token || req.headers['authorization'];
	//decode token
	if(token){
		jwt.verify(token, app.get('secretKey'), function(err, decode){
			if(err){
				return res.json({
					success: false,
					message: 'There was a problem during verification'
				})
			}else{
				req.decode =  decode
				if(decode.exp <= Date.now()/1000){
					return res.status(400).send({status:false,message: 'Token has expired'})
				}
				next();
			}
		})
	}else{
		return res.status(403).send({
			status:false,
			message: 'Token not available '
		});
	}
})
router.get('/profile', function(req, res){
	res.json(req.decode._doc);
});
</code>
</pre>
We have verified token, decode token, and route protection with token. We can also retrieve user data. hopefully this tutorial helps you in the field of security and user verification.

#### Curriculum
- [Setup JWT , Setup Database, Create Router API](https://utopian.io/utopian-io/@alfarisi94/consuming-jwt-api-with-mongodb-and-node-js-part-1-setup-jwt-setup-database-create-router-api)
- [Validate User , Create Token](https://utopian.io/utopian-io/@alfarisi94/consuming-jwt-api-with-mongodb-and-node-js-part-2-validate-user-create-token)
👍 , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , ,