Consuming JWT API with MongoDB and Node.js part-3# Verify Token, Decode Token , Route Protection
utopian-io·@alfarisi94·
0.000 HBDConsuming 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**.  - <code>req.query.token</code> : With <code>req</code> , We can get token from query parameter and with **token='token'**.  - <code>req.headers['authorization']</code>: With <code>req</code> , We can get token by headers['authorization'] in headers with key **'authorization'**.  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'**.  - **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)
👍 ubg, ayay, anharismail, zcool, clayjohn, mvanyi, hakan8686, halitsarpkaya, curx, mys, zapncrap, cifer, jaff8, dandalion, steemnest, littlesteemitph, dandalioncub, gilnambatac, steemfix, steemrent, loshcat, greenorange, utopian-1up, evilest-fiend, barut, layanmarissa, sweeverdev, donjyde, makrotheblack, thinkkniht, kslo, handfree42, sebastiengllmt, carsonroscoe, xplore, onin91, nightdragon, artoraly, naturallife, cheesom, pixelproperty, gydronium, editorspicks, artsyunicorn, femidada, luisrod, parag, berkaytekinsen, varja, kodeblacc, deejee, rsteem, lemony-cricket, exploreand, photohunter4, yourmercury, kekegist, patatesyiyen, petvalbra, sylinda, livsky, fai.zul, bluestorm, pepememes, lemcriq, dysc0rd, bitopia, maphics, jerybanfield, photohunter3, flinter, minersean, helo, flauwy, mahdiyari, simonluisi, mirza-kun, tradeownsystems, stoodkev, dakeshi, ansonoxy, eastmael, jamesbarraclough, espoem, zulfan88, advsamadhan, moorkedi, nathalie13, naideth, family.app, phgnomo, mountainjewel, goddywise4-eu, proffgodswill, bitcoin.news, annyvery1, organicgardener, photohunter1, howtosteem, sampath94, dawa, maribelanzola, sharminwadud, ernoldlvb, kryptogermany, clevershovel, nazmulrana, godsngh1, sazid36, joanpablo, romanleopold, syahrin, mvoalevine, steemit-username, oezixxx, ongolodesire, pinkyangel, jfuenmayor96, smafey, steaknsteem, kimaben, zlatkamrs, isabella394, emailbox19149, aderemi01, killbill73, nonsqtr, crispycoinboys, flugbot, truthtrader, odebgaming, zohaib715, thabiggdogg, yeswanth, photohunter5, criptokingko, opulence, jayo, haejin-sucks, born2crypto, cute-teen, rancho-relaxo, xbox-gamer, special-agent, dyancuex, ronimm, jesdn16, not-a-bird, navx, amosbastian, rhotimee, minnowboosted, roj, jacintoelbarouki, zay-arasi, wise-confucius, flag-haejin, steemit-abuse, elbleess, harshallele, xtramedium, eleonardo, studytext, ilovekrys, solomon507, videosteemit, amirdesaingrafis, azharmaulana, muammarnst, animesukidesu, anime.lovers, sugandhaseth, ahmad097, cryptophunk, ilyastarar, instantania.cat, bhim, maneki-neko, gotgame, silasvogt, masud222, checkthisout, not-a-cat, saifannur-mzy, hmctrasher, tailslide, andiepumpgun, soykatherine, aliyu-s, muratti, mwfiae, nikema, carlitojoshua, daszod, lsanek, lykia, realness, musicbot, masterofdisaster, gnaimul, morin89, niouton, darkassassin, cryptocopy, dotman-art, ewuoso, esme-svh, biplob12, odesanya, senseibabs, camillius, used-lessboy, estherekanem, bryanwilliam, kaell, toninux, fabiocola, soydandan, umut1905, salahudeen, odibezeking, lauraesfeliz, wealth4good, michelios, jdc, animefanrd, devilonwheels, solpaman, steemassistant, depq, hermanasquintero, karinasia25, blancoazx, carmen52, bargolis, phasma, frellarong, carloniere, steemitcanarias, armandofd, jramirezviera, saksham, phogyan, hillaryaa, techmojo, isaganicabrales, idlebright, adhew, shenoy, williams-owb, thescholarlyowl, jrmiller87, kaking, gwapoaller, khairulfahmi92, geezyweezy, kilianparadise, cauac, azwarrangkuti, thinkingmind, ruslanghani, utopian-io, amn, auliausu,