create account

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

View this thread on: hive.blogpeakd.comecency.com
· @alfarisi94 · (edited)
$69.60
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)
👍  , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , and 200 others
properties (23)
authoralfarisi94
permlink6wymfp-consuming-jwt-api-with-mongodb-and-node-js-part-3-verify-token-decode-token-route-protection
categoryutopian-io
json_metadata"{"community":"utopian","app":"utopian/1.0.0","format":"markdown","repository":{"id":27193779,"name":"node","full_name":"nodejs/node","html_url":"https://github.com/nodejs/node","fork":false,"owner":{"login":"nodejs"}},"pullRequests":[],"platform":"github","type":"tutorials","tags":["utopian-io","nodejs","jwt","javascript","web"],"users":["alfarisi94"],"links":["https://utopian.io/utopian-io/@alfarisi94/consuming-jwt-api-with-mongodb-and-node-js-part-1-setup-jwt-setup-database-create-router-api","https://utopian.io/utopian-io/@alfarisi94/consuming-jwt-api-with-mongodb-and-node-js-part-2-validate-user-create-token","https://cdn.utopian.io/posts/8d0f6fc87459ff3e92743f1c4a47aa60b852Screenshot_26.png","https://cdn.utopian.io/posts/f54ad58abdcfddb2937eab4faf47282b3b45Screenshot_27.png","https://cdn.utopian.io/posts/280b754eb3e41754b9b2d456bc38cfb62479Screenshot_28.png","https://cdn.utopian.io/posts/96801dd74cc9cde1e1f5f0b9d6391ba36524Screenshot_30.png"],"image":["https://cdn.utopian.io/posts/8d0f6fc87459ff3e92743f1c4a47aa60b852Screenshot_26.png","https://cdn.utopian.io/posts/f54ad58abdcfddb2937eab4faf47282b3b45Screenshot_27.png","https://cdn.utopian.io/posts/280b754eb3e41754b9b2d456bc38cfb62479Screenshot_28.png","https://cdn.utopian.io/posts/96801dd74cc9cde1e1f5f0b9d6391ba36524Screenshot_30.png"],"moderator":{"account":"portugalcoin","time":"2018-05-02T20:23:05.442Z","pending":false,"reviewed":true,"flagged":false},"questions":{"voters":["portugalcoin"],"answers":[{"question_id":"tuts-1","answer_id":"tuts-1-a-2","user":"portugalcoin","influence":60},{"question_id":"tuts-2","answer_id":"tuts-2-a-1","user":"portugalcoin","influence":60},{"question_id":"tuts-3","answer_id":"tuts-3-a-3","user":"portugalcoin","influence":60},{"question_id":"tuts-4","answer_id":"tuts-4-a-1","user":"portugalcoin","influence":60},{"question_id":"tuts-5","answer_id":"tuts-5-a-3","user":"portugalcoin","influence":60},{"question_id":"tuts-6","answer_id":"tuts-6-a-2","user":"portugalcoin","influence":60},{"question_id":"c-1","answer_id":"c-1-a-2","user":"portugalcoin","influence":60},{"question_id":"c-2","answer_id":"c-2-a-3","user":"portugalcoin","influence":60}],"total_influence":0,"most_rated":[{"question_id":"tuts-1","answer_id":"tuts-1-a-2","influence":60,"voters":["portugalcoin"]},{"question_id":"tuts-2","answer_id":"tuts-2-a-1","influence":60,"voters":["portugalcoin"]},{"question_id":"tuts-3","answer_id":"tuts-3-a-3","influence":60,"voters":["portugalcoin"]},{"question_id":"tuts-4","answer_id":"tuts-4-a-1","influence":60,"voters":["portugalcoin"]},{"question_id":"tuts-5","answer_id":"tuts-5-a-3","influence":60,"voters":["portugalcoin"]},{"question_id":"tuts-6","answer_id":"tuts-6-a-2","influence":60,"voters":["portugalcoin"]},{"question_id":"c-1","answer_id":"c-1-a-2","influence":60,"voters":["portugalcoin"]},{"question_id":"c-2","answer_id":"c-2-a-3","influence":60,"voters":["portugalcoin"]}]},"score":63,"total_influence":60,"staff_pick":null,"staff_pick_by":null,"config":{"questions":[{"question":"How many substantial concepts does this tutorial address?","question_id":"tuts-1","answers":[{"answer":"4-5 substantial concepts covered in the tutorial.","answer_id":"tuts-1-a-1","value":10},{"answer":"2-3 substantial concepts covered in the tutorial.","answer_id":"tuts-1-a-2","value":7},{"answer":"1 substantial concept covered in the tutorial.","answer_id":"tuts-1-a-3","value":3},{"answer":"More than 5 substantial concepts covered in the tutorial.","answer_id":"tuts-1-a-4","value":0}]},{"question":"Does the title and the outline of the tutorial properly reflect the content?","question_id":"tuts-2","answers":[{"answer":"Yes, it is very clear.","answer_id":"tuts-2-a-1","value":15},{"answer":"To some extent.","answer_id":"tuts-2-a-2","value":11.5},{"answer":"The title is somewhat misleading and/or the outline is not detailed or informative enough.","answer_id":"tuts-2-a-3","value":4.5},{"answer":"Title and outline are of little or no relevance to the content of the tutorial.","answer_id":"tuts-2-a-4","value":0}]},{"question":"Did the contributor provide supplementary resources, such as code and sample files in the contribution post or a linked GitHub repository?","question_id":"tuts-3","answers":[{"answer":"Yes, exceptional supplementary resources are provided including a relevant github repo/gist.","answer_id":"tuts-3-a-1","value":15},{"answer":"Supplementary resources provided are of high relevance.","answer_id":"tuts-3-a-2","value":12},{"answer":"Contributor provides minimal supplementary resources.","answer_id":"tuts-3-a-3","value":6},{"answer":"No supplementary resources were provided.","answer_id":"tuts-3-a-4","value":0}]},{"question":"Is the tutorial part of a series?","question_id":"tuts-4","answers":[{"answer":"Yes.","answer_id":"tuts-4-a-1","value":10},{"answer":"Yes, but it is the first entry in the series.","answer_id":"tuts-4-a-2","value":7},{"answer":"No, but it works just fine as a stand-alone tutorial.","answer_id":"tuts-4-a-3","value":5},{"answer":"No.","answer_id":"tuts-4-a-4","value":0}]},{"question":"Does the tutorial contain sufficient explanatory visuals?","question_id":"tuts-5","answers":[{"answer":"Yes, the visual components of the post were adequate in quality and quantity.","answer_id":"tuts-5-a-1","value":10},{"answer":"The volume of visual components included was unnecessarily large.","answer_id":"tuts-5-a-2","value":7},{"answer":"The post lacked sufficient visualization to easily learn from the content.","answer_id":"tuts-5-a-3","value":3},{"answer":"No visualization was presented in this contribution.","answer_id":"tuts-5-a-4","value":0}]},{"question":"How unique and/or innovative are the concepts covered in the tutorial?","question_id":"tuts-6","answers":[{"answer":"This was the first time I read about the concepts covered.","answer_id":"tuts-6-a-1","value":10},{"answer":"The concepts covered were innovative and offer some usefulness.","answer_id":"tuts-6-a-2","value":7},{"answer":"I have read several similar ideas and thoughts elsewhere, but this one was of higher quality.","answer_id":"tuts-6-a-3","value":5},{"answer":"Such tutorials can be found online with great ease and the contribution add no value to the open source community.","answer_id":"tuts-6-a-4","value":0}]},{"question":"How would you describe the formatting, language and overall presentation of the post?","question_id":"c-1","answers":[{"answer":"The post is of very high quality.","answer_id":"c-1-a-1","value":10},{"answer":"The post is of decent quality, but not spectacular in any way.","answer_id":"c-1-a-2","value":7},{"answer":"The post is poorly written and/or formatted, but readable.","answer_id":"c-1-a-3","value":3},{"answer":"The post is really hard to read and the content is barely understandable.","answer_id":"c-1-a-4","value":0}]},{"question":"How would you rate the overall value of this contribution on the open source community and ecosystem?","question_id":"c-2","answers":[{"answer":"This contribution brings great and impactful value, and can be used for applications outside the specific project.","answer_id":"c-2-a-1","value":20},{"answer":"This contribution adds significant value to the open source community and ecosystem, or is of critical importance to the specific project.","answer_id":"c-2-a-2","value":16},{"answer":"This contribution adds some value to the open source community and ecosystem or is only valuable to the specific project.","answer_id":"c-2-a-3","value":8},{"answer":"This contribution adds no value to the open source community and ecosystem or the specific project.","answer_id":"c-2-a-4","value":0}]}]}}"
created2018-05-02 16:25:30
last_update2018-05-03 16:06:03
depth0
children6
last_payout2018-05-09 16:25:30
cashout_time1969-12-31 23:59:59
total_payout_value50.570 HBD
curator_payout_value19.028 HBD
pending_payout_value0.000 HBD
promoted0.000 HBD
body_length7,636
author_reputation5,678,893,550,406
root_title"Consuming JWT API with MongoDB and Node.js part-3# Verify Token, Decode Token , Route Protection"
beneficiaries
0.
accountutopian.pay
weight1,500
max_accepted_payout1,000,000.000 HBD
percent_hbd10,000
post_id53,472,555
net_rshares14,020,854,916,457
author_curate_reward""
vote details (264)
@amn ·
Reall a helpfull tutorial
properties (22)
authoramn
permlinkre-alfarisi94-6wymfp-consuming-jwt-api-with-mongodb-and-node-js-part-3-verify-token-decode-token-route-protection-20180506t085543534z
categoryutopian-io
json_metadata{"tags":["utopian-io"],"app":"steemit/0.1"}
created2018-05-06 08:55:45
last_update2018-05-06 08:55:45
depth1
children1
last_payout2018-05-13 08:55:45
cashout_time1969-12-31 23:59:59
total_payout_value0.000 HBD
curator_payout_value0.000 HBD
pending_payout_value0.000 HBD
promoted0.000 HBD
body_length25
author_reputation1,578,841,540,124
root_title"Consuming JWT API with MongoDB and Node.js part-3# Verify Token, Decode Token , Route Protection"
beneficiaries[]
max_accepted_payout1,000,000.000 HBD
percent_hbd10,000
post_id54,163,603
net_rshares0
@alfarisi94 ·
Thanks @amn
properties (22)
authoralfarisi94
permlinkre-amn-re-alfarisi94-6wymfp-consuming-jwt-api-with-mongodb-and-node-js-part-3-verify-token-decode-token-route-protection-20180506t133544288z
categoryutopian-io
json_metadata{"tags":["utopian-io"],"users":["amn"],"app":"steemit/0.1"}
created2018-05-06 13:35:48
last_update2018-05-06 13:35:48
depth2
children0
last_payout2018-05-13 13:35:48
cashout_time1969-12-31 23:59:59
total_payout_value0.000 HBD
curator_payout_value0.000 HBD
pending_payout_value0.000 HBD
promoted0.000 HBD
body_length11
author_reputation5,678,893,550,406
root_title"Consuming JWT API with MongoDB and Node.js part-3# Verify Token, Decode Token , Route Protection"
beneficiaries[]
max_accepted_payout1,000,000.000 HBD
percent_hbd10,000
post_id54,199,417
net_rshares0
@iqbalhood ·
https://media1.tenor.com/images/80e1a214d74cb68be337a5ffc4635860/tenor.gif?itemid=11764105
properties (22)
authoriqbalhood
permlinkre-alfarisi94-6wymfp-consuming-jwt-api-with-mongodb-and-node-js-part-3-verify-token-decode-token-route-protection-20180508t092325201z
categoryutopian-io
json_metadata{"tags":["utopian-io"],"image":["https://media1.tenor.com/images/80e1a214d74cb68be337a5ffc4635860/tenor.gif?itemid=11764105"],"app":"steemit/0.1"}
created2018-05-08 09:23:27
last_update2018-05-08 09:23:27
depth1
children0
last_payout2018-05-15 09:23:27
cashout_time1969-12-31 23:59:59
total_payout_value0.000 HBD
curator_payout_value0.000 HBD
pending_payout_value0.000 HBD
promoted0.000 HBD
body_length90
author_reputation11,768,748,838,027
root_title"Consuming JWT API with MongoDB and Node.js part-3# Verify Token, Decode Token , Route Protection"
beneficiaries[]
max_accepted_payout1,000,000.000 HBD
percent_hbd10,000
post_id54,535,807
net_rshares0
@james1122 ·
 Awesome post!! Keep it up and check out [THIS POST](https://steemit.com/life/@cryptopaparazzi/chapter-one-let-there-be-the-man-and-there-was-a-man-let-there-be-a-woman-and-there-was-sex) as well as I have something similar. 
properties (22)
authorjames1122
permlinkre-6wymfp-consuming-jwt-api-with-mongodb-and-node-js-part-3-verify-token-decode-token-route-protection-20180502t165633
categoryutopian-io
json_metadata""
created2018-05-02 16:56:33
last_update2018-05-02 16:56:33
depth1
children0
last_payout2018-05-09 16:56:33
cashout_time1969-12-31 23:59:59
total_payout_value0.000 HBD
curator_payout_value0.000 HBD
pending_payout_value0.000 HBD
promoted0.000 HBD
body_length225
author_reputation-1,569,261,196,247
root_title"Consuming JWT API with MongoDB and Node.js part-3# Verify Token, Decode Token , Route Protection"
beneficiaries[]
max_accepted_payout1,000,000.000 HBD
percent_hbd10,000
post_id53,477,801
net_rshares0
@portugalcoin ·
Thank you for the contribution It has been approved.

----------------------------------------------------------------------
Need help? Write a ticket on https://support.utopian.io.
Chat with us on [Discord](https://discord.gg/uTyJkNm).

**[[utopian-moderator]](https://utopian.io/moderators)**
properties (22)
authorportugalcoin
permlinkre-alfarisi94-6wymfp-consuming-jwt-api-with-mongodb-and-node-js-part-3-verify-token-decode-token-route-protection-20180502t202529972z
categoryutopian-io
json_metadata{"tags":["utopian-io"],"community":"utopian","app":"utopian/1.0.0"}
created2018-05-02 20:25:30
last_update2018-05-02 20:25:30
depth1
children0
last_payout2018-05-09 20:25:30
cashout_time1969-12-31 23:59:59
total_payout_value0.000 HBD
curator_payout_value0.000 HBD
pending_payout_value0.000 HBD
promoted0.000 HBD
body_length294
author_reputation602,506,495,081,078
root_title"Consuming JWT API with MongoDB and Node.js part-3# Verify Token, Decode Token , Route Protection"
beneficiaries
0.
accountutopian.pay
weight1,500
max_accepted_payout1,000,000.000 HBD
percent_hbd10,000
post_id53,508,804
net_rshares0
@utopian-io ·
#### Hey @alfarisi94
We're already looking forward to your next contribution!

##### Utopian Witness!
<a href="https://v2.steemconnect.com/sign/account-witness-vote?witness=utopian-io&approve=1">Vote for Utopian Witness!</a> We are made of developers, system administrators, entrepreneurs, artists, content creators, thinkers. We embrace every nationality, mindset and belief.

**Want to chat? Join us on Discord https://discord.gg/h52nFrV**
properties (22)
authorutopian-io
permlinkre-alfarisi94-6wymfp-consuming-jwt-api-with-mongodb-and-node-js-part-3-verify-token-decode-token-route-protection-20180505t150240718z
categoryutopian-io
json_metadata{"tags":["utopian-io"],"users":["alfarisi94"],"links":["https://v2.steemconnect.com/sign/account-witness-vote?witness=utopian-io&approve=1","https://discord.gg/h52nFrV"],"app":"steemit/0.1"}
created2018-05-05 15:02:39
last_update2018-05-05 15:02:39
depth1
children0
last_payout2018-05-12 15:02:39
cashout_time1969-12-31 23:59:59
total_payout_value0.000 HBD
curator_payout_value0.000 HBD
pending_payout_value0.000 HBD
promoted0.000 HBD
body_length441
author_reputation152,955,367,999,756
root_title"Consuming JWT API with MongoDB and Node.js part-3# Verify Token, Decode Token , Route Protection"
beneficiaries[]
max_accepted_payout1,000,000.000 HBD
percent_hbd10,000
post_id54,037,973
net_rshares0