{"id":2969,"date":"2015-11-02T08:15:15","date_gmt":"2015-11-02T04:15:15","guid":{"rendered":"http:\/\/nayarweb.com\/blog\/?p=2969"},"modified":"2015-11-02T08:17:33","modified_gmt":"2015-11-02T04:17:33","slug":"protect-your-nodejsexpress-routes-with-http-basic-auth","status":"publish","type":"post","link":"https:\/\/nayarweb.com\/blog\/2015\/protect-your-nodejsexpress-routes-with-http-basic-auth\/","title":{"rendered":"Protect your NodeJS\/Express routes with HTTP Basic Auth"},"content":{"rendered":"<p>Not all parts of your website or REST APIs you do require same level of protection. For example, a <code>GET \/api\/dimounes<\/code> is pretty harmless.<\/p>\n<p>The Express\/NodeJS code for such a route may be like follows:<\/p>\n<pre>\r\napp.get('\/api\/dimounes\/',function(req,res){\r\n  var rows = \/\/ Get the people from database, file or anywhere\r\n  res.send(rows);\r\n});\r\n<\/pre>\n<p>Let&#8217;s say now you want to add more &#8216;dimoune&#8217;. We create a new route for it but we&#8217;ll use HTTP POST verb instead of GET.<\/p>\n<pre>\r\napp.use(bodyParser.urlencoded({extended: true }));\r\napp.use(bodyParser.json());\r\n\r\napp.post('\/api\/dimounes\/',function(req,res){\r\n  var sql = \"INSERT INTO dimounes (name,sex) VALUES ('\" + req.body.name + \"' , \" + req.body.sex + \");\";\r\n  \/\/ run sql or mongo insert\r\n  res.send(\"ok\");\r\n});\r\n<\/pre>\n<p>Problem here is everyone can do POST request and spam your database to corrupt it. Let&#8217;s protect the POST route so that it requires the user to authenticate.<\/p>\n<pre>$ npm install http-auth --save<\/pre>\n<p>Let&#8217;s define our username and password<\/p>\n<pre>\r\nvar auth = require('http-auth');\r\nvar basic = auth.basic({\r\n        realm: \"Protected Area\"\r\n    }, function (username, password, callback) { \/\/ Custom authentication method.\r\n        callback(username === \"nayar\" && password === \"mydumbpassword\");\r\n    }\r\n);\r\n<\/pre>\n<p>All we have to do is add <code>auth.connect(basic)<\/code> as a middleware in our routes we want to protect<\/p>\n<pre>\r\napp.post('\/api\/dimounes\/',auth.connect(basic),function(req,res){\r\n  var sql = \"INSERT INTO dimounes (name,sex) VALUES ('\" + req.body.name + \"' , \" + req.body.sex + \");\";\r\n  \/\/ run sql or mongo insert\r\n  res.send(\"ok\");\r\n});\r\n<\/pre>\n<p>And there you go! Let&#8217;s try it with AJAX calls with jQuery \ud83d\ude09<\/p>\n<pre>\r\n$.ajax({\r\n  method: \"post\",\r\n  url: \"\/api\/dimounes\/\",\r\n  data: {\r\n    name : \"Nayar\",\r\n    sex: \"male\"\r\n  },\r\n  success: function( data ) {\r\n    console.log(data);\r\n  },\r\n  });\r\n<\/pre>\n<p>You shall get a popup in your browser asking for your username and password. If you are using curl, just add the credentials using the <code>-u<\/code><\/p>\n<pre>curl -nayar:mydumbpassword -H \"Content-Type:application\/json\" -X POST --data '{\"name\":\"nayar\",\"sex\":\"male\"}' http:\/\/example.com\/api\/dimounes<\/pre>\n<p>NOTE: As we saw in <a href=\"https:\/\/nayarweb.com\/blog\/2015\/wtf-express-just-give-me-my-body-nodejs\/\">this article (click)<\/a>, Express doesn&#8217;t parse HTTP body, we have to add this line at the top for the above command to work in curl. <\/p>\n<pre>app.use(bodyParser.json());<\/pre>\n","protected":false},"excerpt":{"rendered":"<p>Not all parts of your website or REST APIs you do require same level of protection. For example, a GET \/api\/dimounes is pretty harmless. The Express\/NodeJS code for such a route may be like follows: app.get(&#8216;\/api\/dimounes\/&#8217;,function(req,res){ var rows = \/\/ Get the people from database, file or anywhere res.send(rows); }); Let&#8217;s say now you want &hellip; <a href=\"https:\/\/nayarweb.com\/blog\/2015\/protect-your-nodejsexpress-routes-with-http-basic-auth\/\" class=\"continue-reading\">Continue reading <span class=\"screen-reader-text\">Protect your NodeJS\/Express routes with HTTP Basic Auth<\/span><\/a><\/p>\n","protected":false},"author":1,"featured_media":0,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[210,1],"tags":[215,217],"class_list":["post-2969","post","type-post","status-publish","format-standard","hentry","category-technology","category-uncategorized","tag-nodejs","tag-rest-api"],"_links":{"self":[{"href":"https:\/\/nayarweb.com\/blog\/wp-json\/wp\/v2\/posts\/2969","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/nayarweb.com\/blog\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/nayarweb.com\/blog\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/nayarweb.com\/blog\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/nayarweb.com\/blog\/wp-json\/wp\/v2\/comments?post=2969"}],"version-history":[{"count":10,"href":"https:\/\/nayarweb.com\/blog\/wp-json\/wp\/v2\/posts\/2969\/revisions"}],"predecessor-version":[{"id":2979,"href":"https:\/\/nayarweb.com\/blog\/wp-json\/wp\/v2\/posts\/2969\/revisions\/2979"}],"wp:attachment":[{"href":"https:\/\/nayarweb.com\/blog\/wp-json\/wp\/v2\/media?parent=2969"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/nayarweb.com\/blog\/wp-json\/wp\/v2\/categories?post=2969"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/nayarweb.com\/blog\/wp-json\/wp\/v2\/tags?post=2969"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}