﻿
{"id":9393,"date":"2018-09-16T14:25:26","date_gmt":"2018-09-16T14:25:26","guid":{"rendered":"http:\/\/www.gencayyildiz.com\/blog\/?p=9393"},"modified":"2018-09-16T14:25:26","modified_gmt":"2018-09-16T14:25:26","slug":"node-js-jwt-ile-token-olusturma","status":"publish","type":"post","link":"https:\/\/www.gencayyildiz.com\/blog\/node-js-jwt-ile-token-olusturma\/","title":{"rendered":"Node.js &#8211; JWT \u0130le Token Olu\u015fturma"},"content":{"rendered":"<div id=\"fb-root\"><\/div>\n<p>Merhaba,<\/p>\n<p>API servisleri, do\u011fal yap\u0131lar\u0131 gere\u011fi d\u0131\u015far\u0131dan eri\u015febilen herkese i\u015flevine uygun sonu\u00e7lar d\u00f6nd\u00fcrebilen mekanizmalard\u0131r. Tabi \u00e7al\u0131\u015fma s\u00fcrecinde API servislerinin kulland\u0131\u011f\u0131 altyap\u0131lar veyahut veritabanlar\u0131 kritik bilgiler arz ediyorsa bu API&#8217;lara herkesin eri\u015fmesini istemeyiz. Dolay\u0131s\u0131yla belli ba\u015fl\u0131 validasyonlar geli\u015ftirir ve uzaktan do\u011frulama ile oturum bilgisi elde edebilen kullan\u0131c\u0131lar\u0131n API&#8217;lara eri\u015febilme hakk\u0131n\u0131 veririz. Geli\u015ftirilen bu do\u011frulama y\u00f6ntemlerinden biri olan JWT, API yap\u0131lar\u0131nda JSON Web Token ile kullan\u0131c\u0131 ad\u0131 ve \u015fifre bilgileriyle yap\u0131lan do\u011frulama neticesinde elde edilen token ile uzaktaki kullan\u0131c\u0131n\u0131n API&#8217;a eri\u015febilme yetkisini vermektedir.<\/p>\n<p>Bu i\u00e7eri\u011fimizde Node.js&#8217;de JWT ile Token olu\u015fturmay\u0131 inceleyece\u011fiz ve Node.js&#8217;de bu i\u015flemler i\u00e7in geli\u015ftirilmi\u015f <a href=\"https:\/\/github.com\/auth0\/node-jsonwebtoken\" rel=\"noopener\" target=\"_blank\">node-jsonwebtoken<\/a> mod\u00fcl\u00fcn\u00fc kullanaca\u011f\u0131z. Makalemizde konuyu daha anla\u015f\u0131l\u0131r k\u0131labilmek i\u00e7in \u00f6rnek bir senaryo \u00fczerinden seyredece\u011fiz ve kullan\u0131c\u0131 taraf\u0131ndan al\u0131nan kullan\u0131c\u0131 ad\u0131 ve \u015fifre bilgilerini MongoDB veritaban\u0131nda bulunan &#8220;users&#8221; collection\u0131nda do\u011frulama neticesinde token olu\u015fumunu ger\u00e7ekle\u015ftirece\u011fiz.<br \/>\n<div id=\"attachment_9405\" style=\"width: 811px\" class=\"wp-caption aligncenter\"><a href=\"http:\/\/www.gencayyildiz.com\/blog\/wp-content\/uploads\/2018\/09\/Node.js-JWT-\u0130le-Token-Olu\u015fturma.png\"><img loading=\"lazy\" decoding=\"async\" aria-describedby=\"caption-attachment-9405\" src=\"http:\/\/www.gencayyildiz.com\/blog\/wp-content\/uploads\/2018\/09\/Node.js-JWT-\u0130le-Token-Olu\u015fturma.png\" alt=\"Node.js - JWT \u0130le Token Olu\u015fturma\" width=\"801\" height=\"138\" class=\"size-full wp-image-9405\" srcset=\"https:\/\/www.gencayyildiz.com\/blog\/wp-content\/uploads\/2018\/09\/Node.js-JWT-\u0130le-Token-Olu\u015fturma.png 801w, https:\/\/www.gencayyildiz.com\/blog\/wp-content\/uploads\/2018\/09\/Node.js-JWT-\u0130le-Token-Olu\u015fturma-300x52.png 300w, https:\/\/www.gencayyildiz.com\/blog\/wp-content\/uploads\/2018\/09\/Node.js-JWT-\u0130le-Token-Olu\u015fturma-768x132.png 768w\" sizes=\"auto, (max-width: 801px) 100vw, 801px\" \/><\/a><p id=\"caption-attachment-9405\" class=\"wp-caption-text\">Users Collection&#8217;\u0131<\/p><\/div><\/p>\n<h3>Kurulum<\/h3>\n<p>JsonWebToken mod\u00fcl\u00fcn\u00fc kurup, projeye entegrasyonunu sa\u011flamak i\u00e7in a\u015fa\u011f\u0131daki komutu \u00e7al\u0131\u015ft\u0131rman\u0131z yeterlidir.<\/p>\n<pre class=\"brush: plain; title: ; notranslate\" title=\"\">\r\nnpm install jsonwebtoken --save\r\n<\/pre>\n<h3>Alt Yap\u0131n\u0131n Olu\u015fturulmas\u0131<\/h3>\n<p>Kullan\u0131c\u0131dan al\u0131nacak bilgileri elde edebilmek i\u00e7in <a href=\"http:\/\/www.gencayyildiz.com\/blog\/node-jsde-body-parser-modulu-ile-post-edilen-datayi-yakalamak\/\" rel=\"noopener\" target=\"_blank\">Body-Parser<\/a> ve MongoDB veritaban\u0131 i\u015flemlerini ger\u00e7ekle\u015ftirebilmek i\u00e7in <a href=\"http:\/\/www.gencayyildiz.com\/blog\/node-js-mongodbye-mongoose-modulu-ile-baglanma\/\" rel=\"noopener\" target=\"_blank\">Mongoose<\/a> mod\u00fcllerini install ediyoruz ve referans verilen adreslerde oldu\u011fu gibi gerekli temel ayarlar\u0131 yap\u0131yoruz. Dolay\u0131s\u0131yla ana mod\u00fcl\u00fcm\u00fcz\u00fc a\u015fa\u011f\u0131daki gibi in\u015fa ediyoruz.<\/p>\n<pre class=\"brush: jscript; title: ; notranslate\" title=\"\">\r\n--- app.js ---\r\nconst app = require(&quot;express&quot;)();\r\nconst bodyParser = require(&quot;body-parser&quot;);\r\n\r\nrequire(&quot;.\/db\/db&quot;)();\r\n\r\napp.set(&quot;api_secret_key&quot;, require(&quot;.\/config&quot;).api_secret_key);\r\napp.use(bodyParser.json());\r\napp.use(bodyParser.urlencoded({ extended: true }));\r\n\r\napp.use(&quot;\/user&quot;, require(&quot;.\/routers\/userRouter&quot;));\r\napp.listen(5000, () =&gt; console.log(&quot;Yay\u0131n ba\u015flad\u0131...&quot;));\r\n<\/pre>\n<p>Daha token olu\u015fturma yap\u0131s\u0131na gelmeden \u00f6nce bu ana mod\u00fcl\u00fcm\u00fcz olan app.js dosyas\u0131 i\u00e7erisinde yap\u0131lan baz\u0131 i\u015flemlerin \u00fczerinde durmam\u0131z gerekmektedir. Bunlardan ilki, &#8220;api_secret_key&#8221; isminde tan\u0131mlanan global de\u011fi\u015fkenimizdir. Dikkat ederseniz e\u011fer ilgili de\u011fi\u015fkenin de\u011feri &#8220;config.js&#8221; isimli bir s\u0131n\u0131f i\u00e7erisindeki &#8220;api_secret_key&#8221; \u00f6zelli\u011finden getirilmektedir. Anlam olarak gizli anahtar olan bu de\u011ferin nedenini a\u00e7\u0131klamam\u0131z gerekirse e\u011fer hemen <a href=\"http:\/\/www.gencayyildiz.com\/blog\/json-web-tokenjwt-nedir\/\" rel=\"noopener\" target=\"_blank\">JSON Web Token(JWT) Nedir?<\/a> ba\u015fl\u0131kl\u0131 makaleme sizleri davet ediyorum. \u0130lgili makalede token yap\u0131s\u0131n\u0131n fiziksel anatomisini incelemi\u015ftik ve Verify Signature k\u0131sm\u0131nda taraf\u0131m\u0131zdan belirlenmi\u015f gizli anahtar\u0131n ta\u015f\u0131nabilece\u011fini belirtmi\u015ftik. \u0130\u015fte bu global de\u011fi\u015fken, token yap\u0131s\u0131nda kullanaca\u011f\u0131m\u0131z bu gizli anahtar\u0131 bize getirecektir. <em>Neden global olarak tan\u0131mland\u0131?<\/em> sorusuna kar\u015f\u0131l\u0131k olarak birden fazla http fonksiyonunda ayn\u0131 anahtar\u0131 kullanabilme ihtimalimizin olmas\u0131ndan dolay\u0131 bu \u015fekilde global olarak tan\u0131mlanmas\u0131n\u0131 tercih etmi\u015f bulunmaktay\u0131m. Tabi bizler \u00f6rne\u011fimizde tek bir http fonksiyonu \u00fczerinden \u00f6rneklendirme yapaca\u011f\u0131z. Lakin sizlere de\u011fi\u015fken ve l\u00fczumsuz kod tasarrufu a\u00e7\u0131s\u0131ndan bu mant\u0131\u011f\u0131 hat\u0131rlatmak i\u00e7in bu \u015fekilde bir \u00f6rneklendirme yapmay\u0131 uygun g\u00f6rd\u00fcm.<\/p>\n<pre class=\"brush: jscript; title: ; notranslate\" title=\"\">\r\nmodule.exports = {\r\n    api_secret_key: &quot;laylaylom galiba sana g\u00f6re sevmeler&quot;\r\n};\r\n<\/pre>\n<p>Evet&#8230; G\u00f6rd\u00fc\u011f\u00fcn\u00fcz gibi &#8220;config.js&#8221; mod\u00fcl\u00fcn\u00fcn detay\u0131da yukar\u0131daki gibidir. Siz istedi\u011finiz gizli anahtar de\u011ferini belirtebilirsiniz&#8230;<\/p>\n<p>\u0130kinci olarak &#8220;userRouter&#8221; isimli mod\u00fcl i\u00e7erisinde route \u00e7al\u0131\u015fmalar\u0131m\u0131z\u0131 ger\u00e7ekle\u015ftirdi\u011fimize dikkatinizi \u00e7ekerim.<\/p>\n<p>Hadi buyrun ba\u015flayal\u0131m.<\/p>\n<h3>Token Olu\u015fturma<\/h3>\n<p>Burada kullan\u0131c\u0131dan al\u0131nan kullan\u0131c\u0131 ad\u0131 ve \u015fifre veritaban\u0131nda do\u011frulanacak ve bu do\u011frulama neticesinde token olu\u015fturulacakt\u0131r. O y\u00fczden ilgili route \u00e7al\u0131\u015fmam\u0131z ve algoritmas\u0131 a\u015fa\u011f\u0131daki gibi olacakt\u0131r.<\/p>\n<pre class=\"brush: jscript; title: ; notranslate\" title=\"\">\r\nconst router = require(&quot;express&quot;).Router();\r\nconst bcrypt = require(&quot;bcryptjs&quot;);\r\nconst jwt = require(&quot;jsonwebtoken&quot;);\r\n\r\nconst userModel = require(&quot;..\/models\/user&quot;);\r\n\r\nrouter.post(&quot;\/getToken&quot;, (request, response, next) =&gt; {\r\n    const { userName, password } = request.body;\r\n    userModel.findOne({ userName })\r\n        .then(data =&gt; {\r\n            \/\/Girilen userName de\u011ferinde bir kay\u0131t varsa buras\u0131 \u00e7al\u0131\u015facakt\u0131r.\r\n            bcrypt.compare(password, data.password)\r\n                .then(data =&gt; {\r\n                    \/\/Veritaban\u0131ndaki \u015fifrelenmi\u015f password ile kullan\u0131c\u0131dan al\u0131nan password birbirlerini do\u011fruluyorsa e\u011fer data de\u011feri true gelecektir. Aksi taktirde false de\u011feri gelecektir.\r\n                    if (!data)\r\n                        response.send(&quot;Kullan\u0131c\u0131 ad\u0131 veya \u015fifre yanl\u0131\u015f...&quot;);\r\n                    else {\r\n                        \/\/E\u011fer data parametresi true de\u011ferinde geldiyse token olu\u015fturulacakt\u0131r.\r\n                        const payLoad = { userName, password };\r\n                        const token = jwt.sign(payLoad, request.app.get(&quot;api_secret_key&quot;), { expiresIn: 120\/*dk*\/ });\r\n                        response.json({\r\n                            status: true,\r\n                            userName,\r\n                            password,\r\n                            token\r\n                        });\r\n                    }\r\n                });\r\n        })\r\n        .catch(error =&gt; console.log(&quot;Beklenmeyen bir hatayla kar\u015f\u0131la\u015f\u0131ld\u0131...&quot;));\r\n});\r\n\r\nmodule.exports = router;\r\n<\/pre>\n<p>Yukar\u0131daki kod blo\u011funu incelerseniz e\u011fer asl\u0131nda t\u00fcm mevzu 18 ile 26. sat\u0131rlar aras\u0131nda ge\u00e7mektedir. &#8220;JsonWebToken&#8221; mod\u00fcl\u00fcn\u00fcn &#8220;sign&#8221; fonksiyonu ilk parametre olarak &#8220;Payload&#8221;, ikinci parametreye gizli anahtar ve \u00fc\u00e7\u00fcnc\u00fc parametreye ise token ile ilgili settings objesi almaktad\u0131r. Dolay\u0131s\u0131yla verilen bu de\u011ferler neticesinde her t\u00fcrl\u00fc token de\u011feri olu\u015fturulacakt\u0131r. Biz burada kullan\u0131c\u0131 ad\u0131 ve \u015fifre do\u011frulamas\u0131 neticesinde bu do\u011frulamaya istinaden bir token olu\u015fturmu\u015f olduk. Maksad\u0131m\u0131z biraz daha ger\u00e7ek\u00e7i \u00f6rneklendirmelerle yap\u0131n\u0131n kullan\u0131m alan\u0131n\u0131 ve tarz\u0131n\u0131 daha da netle\u015ftirmektedir. Ayr\u0131ca &#8220;expiresIn&#8221;, token\u0131n ge\u00e7erlilik s\u00fcresini dakika cinsinden tutan bir \u00f6zelliktir.<br \/>\n<a href=\"http:\/\/www.gencayyildiz.com\/blog\/wp-content\/uploads\/2018\/09\/Node.js-JWT-\u0130le-Token-Olu\u015fturma-1.png\"><img loading=\"lazy\" decoding=\"async\" src=\"http:\/\/www.gencayyildiz.com\/blog\/wp-content\/uploads\/2018\/09\/Node.js-JWT-\u0130le-Token-Olu\u015fturma-1.png\" alt=\"Node.js - JWT \u0130le Token Olu\u015fturma\" width=\"1365\" height=\"426\" class=\"aligncenter size-full wp-image-9415\" srcset=\"https:\/\/www.gencayyildiz.com\/blog\/wp-content\/uploads\/2018\/09\/Node.js-JWT-\u0130le-Token-Olu\u015fturma-1.png 1365w, https:\/\/www.gencayyildiz.com\/blog\/wp-content\/uploads\/2018\/09\/Node.js-JWT-\u0130le-Token-Olu\u015fturma-1-300x94.png 300w, https:\/\/www.gencayyildiz.com\/blog\/wp-content\/uploads\/2018\/09\/Node.js-JWT-\u0130le-Token-Olu\u015fturma-1-768x240.png 768w, https:\/\/www.gencayyildiz.com\/blog\/wp-content\/uploads\/2018\/09\/Node.js-JWT-\u0130le-Token-Olu\u015fturma-1-1024x320.png 1024w\" sizes=\"auto, (max-width: 1365px) 100vw, 1365px\" \/><\/a><\/p>\n<p>G\u00f6rd\u00fc\u011f\u00fcn\u00fcz gibi istenilen de\u011ferler e\u015fli\u011finde olu\u015fturulan Payload ile token de\u011ferimizi olu\u015fturmu\u015f bulunmaktay\u0131z. Art\u0131k bu token ile belirtilen ya\u015fam\/ge\u00e7erlilik s\u00fcresi boyunca API \u00fczerinden t\u00fcm i\u015flemleri icra edebiliriz. Tabi bu i\u015flemler i\u00e7inde sonraki makalelerimizde Node.js ile \u00fcretilmi\u015f bir token\u0131n nas\u0131l kullan\u0131ld\u0131\u011f\u0131na dair kapsaml\u0131 bir i\u00e7erik ile sizleri a\u011f\u0131rlayaca\u011f\u0131m \ud83d\ude09<\/p>\n<p>O halde sonraki makalelerimizde g\u00f6r\u00fc\u015fmek \u00fczere diyelim&#8230;<\/p>\n<p>\u0130lgilenenlerin faydalanmas\u0131 dile\u011fiyle&#8230;<br \/>\n\u0130yi \u00e7al\u0131\u015fmalar&#8230;<\/p>\n<!-- AddThis Advanced Settings generic via filter on the_content --><!-- AddThis Share Buttons generic via filter on the_content -->","protected":false},"excerpt":{"rendered":"<p>Merhaba, API servisleri, do\u011fal yap\u0131lar\u0131 gere\u011fi d\u0131\u015far\u0131dan eri\u015febilen herkese i\u015flevine uygun sonu\u00e7lar d\u00f6nd\u00fcrebilen mekanizmalard\u0131r. Tabi \u00e7al\u0131\u015fma s\u00fcrecinde API servislerinin kulland\u0131\u011f\u0131 altyap\u0131lar veyahut veritabanlar\u0131 kritik bilgiler arz ediyorsa bu API&#8217;lara herkesin eri\u015fmesini istemeyiz. Dolay\u0131s\u0131yla belli&#46;&#46;&#46;<!-- AddThis Advanced Settings generic via filter on get_the_excerpt --><!-- AddThis Share Buttons generic via filter on get_the_excerpt --><\/p>\n","protected":false},"author":1,"featured_media":8600,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[2495,2145],"tags":[2609,2610,2620,2622,2621,2624,2623,2625],"class_list":["post-9393","post","type-post","status-publish","format-standard","has-post-thumbnail","hentry","category-express-js","category-node-js","tag-json-web-token","tag-jwt","tag-node-jsonwebtoken","tag-node-js-json-web-token","tag-node-js-jwt","tag-node-js-token","tag-node-js-token-olusturma","tag-token-olusturma"],"amp_enabled":true,"_links":{"self":[{"href":"https:\/\/www.gencayyildiz.com\/blog\/wp-json\/wp\/v2\/posts\/9393","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/www.gencayyildiz.com\/blog\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/www.gencayyildiz.com\/blog\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/www.gencayyildiz.com\/blog\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/www.gencayyildiz.com\/blog\/wp-json\/wp\/v2\/comments?post=9393"}],"version-history":[{"count":23,"href":"https:\/\/www.gencayyildiz.com\/blog\/wp-json\/wp\/v2\/posts\/9393\/revisions"}],"predecessor-version":[{"id":9418,"href":"https:\/\/www.gencayyildiz.com\/blog\/wp-json\/wp\/v2\/posts\/9393\/revisions\/9418"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/www.gencayyildiz.com\/blog\/wp-json\/wp\/v2\/media\/8600"}],"wp:attachment":[{"href":"https:\/\/www.gencayyildiz.com\/blog\/wp-json\/wp\/v2\/media?parent=9393"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/www.gencayyildiz.com\/blog\/wp-json\/wp\/v2\/categories?post=9393"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/www.gencayyildiz.com\/blog\/wp-json\/wp\/v2\/tags?post=9393"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}