<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0" xmlns:atom="http://www.w3.org/2005/Atom" xmlns:dc="http://purl.org/dc/elements/1.1/">
  <channel>
    <title>DEV Community: anasaijaz</title>
    <description>The latest articles on DEV Community by anasaijaz (@anasaijaz).</description>
    <link>https://dev.to/anasaijaz</link>
    <image>
      <url>https://media2.dev.to/dynamic/image/width=90,height=90,fit=cover,gravity=auto,format=auto/https:%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Fuser%2Fprofile_image%2F668532%2F999e0120-5ffd-4dce-bc37-7932b1c25088.png</url>
      <title>DEV Community: anasaijaz</title>
      <link>https://dev.to/anasaijaz</link>
    </image>
    <atom:link rel="self" type="application/rss+xml" href="https://dev.to/feed/anasaijaz"/>
    <language>en</language>
    <item>
      <title>Basic authentication : Vanilla JS</title>
      <dc:creator>anasaijaz</dc:creator>
      <pubDate>Fri, 16 Jul 2021 23:26:16 +0000</pubDate>
      <link>https://dev.to/anasaijaz/basic-authentication-vanilla-js-3fc</link>
      <guid>https://dev.to/anasaijaz/basic-authentication-vanilla-js-3fc</guid>
      <description>&lt;p&gt;Ever thought of how websites and web server protect their secret behind the door well it's not much different than the real world &lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;
You buy a security system 
&lt;/li&gt;

&lt;li&gt;
You lock your stuff behind the security system 
&lt;/li&gt;


&lt;/ol&gt;

&lt;p&gt;Easy right? Just like there are different types of security system available for real world we have different type of systems for the web too &lt;br&gt;
Some of the popular ones are : &lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;
  &lt;b&gt;Basic Authentication&lt;/b&gt;
&lt;/li&gt;

&lt;li&gt;
Bearer/Token Authentication
&lt;/li&gt;


&lt;li&gt;
OAuth Authentication
&lt;/li&gt;


&lt;/ul&gt;

&lt;p&gt;Basic Authentication is the oldest of the authentication available it's not much popular now &lt;br&gt;
But before understanding more advanced authentications it's absolute neccesarry &lt;/p&gt;

&lt;p&gt;so fire up your node and let's understand the authentication process&lt;/p&gt;

&lt;p&gt;&lt;b&gt;Create a folder Tutorial&lt;/b&gt;&lt;br&gt;
In here all of our backend code will lie&lt;br&gt;
&lt;code&gt;mkdir Tutorial&lt;/code&gt;&lt;br&gt;
initialize the npm using &lt;code&gt;npm init&lt;/code&gt; command&lt;/p&gt;

&lt;p&gt;once initialized install express from npm and add to the dependency list&lt;br&gt;
&lt;code&gt;npm install express --save&lt;/code&gt;&lt;/p&gt;

&lt;p&gt;once express is installed make a app.js file in the root directory and load the express module&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;
const express = require("express")
const app = express()

process.env.PORT = 3000

app.get("/" , (req ,res)=&amp;gt;{
    res.status(200).send({"STATUS":"SUCCESS"})
})

app.listen(3000 , ()=&amp;gt;{
    console.log(`STARTED LISTENING ON PORT ${process.env.PORT}`)
});

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;we also created our first route the root route &lt;/p&gt;

&lt;p&gt;run your node server by &lt;br&gt;
&lt;code&gt;node app.js&lt;/code&gt;&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fcj9tuzbioqecorsr9kc6.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fcj9tuzbioqecorsr9kc6.png" alt="image" width="220" height="73"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;let's lock out root route behind a middle ware function which will first authenticate the user with the secret&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;
const isAuthenticated = (req , res , next)=&amp;gt;{
    next()
}

app.get("/" ,isAuthenticated, (req ,res)=&amp;gt;{
    res.status(200).send({"STATUS":"SUCCESS"})
})

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;and then modifying the middle ware function to check the user provided credential against the credential stored on the server&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;
const credentials = {secretName:"Anas Aijaz" , secretPassword:"Catsaresosus"}

const isAuthenticated = (req , res , next)=&amp;gt;{
    const [name , password] = ["Anas Aijaz" , "Dogsaresosus"]

    // We will add code here later

    if(name===credentials.secretName &amp;amp;&amp;amp; password===credentials.secretPassword){
        // The User is authenticated
        return next()
    }

    // User is not authenticated give a reponse 401
    res.set('WWW-Authenticate', 'Basic realm="Access to Index"')
    res.status(401).send("Unauthorised access")


}

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;notice how we delibrately provided a wrong password&lt;br&gt;
let's see what response we get in browser &lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fsok82r6ajq4xso5zcs3a.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fsok82r6ajq4xso5zcs3a.png" alt="image" width="168" height="36"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Oops you the content is locked now and needs a right secret to open&lt;/p&gt;

&lt;p&gt;let's work our way through the front end to take input from the user and  send it to the server&lt;/p&gt;

&lt;p&gt;create a folder beside the Tutorial folder named client and add a index.html index.js in it&lt;/p&gt;

&lt;p&gt;&lt;code&gt;cd ../ &amp;amp;&amp;amp; mkdir client &amp;amp;&amp;amp; cd client &amp;amp;&amp;amp; touch index.html index.js&lt;/code&gt;&lt;/p&gt;

&lt;p&gt;now create a basic form in the html to take input from the user &lt;br&gt;
and on the pressing of the submit button we will use the fetch API to post the data to the server&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt; &amp;lt;form&amp;gt;
            &amp;lt;label&amp;gt;username&amp;lt;/label&amp;gt;
            &amp;lt;input name="username" type="text"/&amp;gt;


            &amp;lt;label&amp;gt;password&amp;lt;/label&amp;gt;
            &amp;lt;input type="password" name="password"/&amp;gt;

            &amp;lt;input type="submit"/&amp;gt;
        &amp;lt;/form&amp;gt;

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;and the javascript to prevent reloading of the page and execute a fetch request from behind&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt; document.addEventListener("submit" , (event)=&amp;gt;{
                  event.preventDefault()
               })
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;ok take the input from the user and store it in the variable &lt;code&gt;username&lt;/code&gt; and &lt;code&gt;password&lt;/code&gt; &lt;/p&gt;

&lt;p&gt;now let's focus on creating a fetch request to our server this fetch request will lie inside the submit event listener&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt; fetch("http://localhost:3000/" , {})
               .then(()=&amp;gt;{})
               .catch(()=&amp;gt;{
                   console.log("an error occured")
               })
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;the skeleton of fetch request will looks like this&lt;/p&gt;

&lt;p&gt;the object passed besides the URI will be the header of our HTTP request&lt;/p&gt;

&lt;p&gt;the Header fields of any http request exists in pairs &lt;br&gt;
KEY:VALUE&lt;br&gt;
for example one of the most basic header will be &lt;br&gt;
"Accept: application/json" this will indicate the server that the client will only accept json as a response&lt;/p&gt;

&lt;p&gt;just like we can add a "Authorization" key the value of which will be the type of authentication and our email and password separated by a colon ":" encoded in a base64 format so it can be transmitted over the web&lt;/p&gt;

&lt;p&gt;"Authorizaton: Basic "&lt;/p&gt;

&lt;p&gt;The Headers interface of the fetch api can be conviently used to place these headers in our request&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt; const headers = new Headers()
 headers.append("Accept" , "application/json")
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;next task is to encode our username:password string into a base64 string we can use the a method of the root window element&lt;/p&gt;

&lt;p&gt;const base64data = window.btoa(&lt;code&gt;${username}:${password}&lt;/code&gt;)&lt;/p&gt;

&lt;p&gt;now it's time to append this to our header with the Basic keyword&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;const auth = &lt;code&gt;Basic ${base64data}&lt;/code&gt;&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;now our fetch requests look like&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;
fetch("http://localhost:3000/", { headers:headers })
      .then(()=&amp;gt;{})
      .catch(()=&amp;gt;{
         console.log("an error occured")
      })
})

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;this will send a request to our server with the proper credentials &lt;/p&gt;

&lt;p&gt;now on the server side we have to get the request and parse the username and password separately&lt;/p&gt;

&lt;p&gt;let's do it in your app.js&lt;/p&gt;

&lt;p&gt;in the middle ware function we have to first get the authorization headers and then base64 decode the credential after splitting the BASIC part&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;
 const encodedAuth = (req.headers.authorization || '')
    .split(' ')[1] || '' // getting the part after Basic

 const [name, password] = Buffer.from(encodedAuth, 'base64')
    .toString().split(':')

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;after splitting the Basic and base64 part we decoded the string and the again splitting it at ":" (remember we added username:password) &lt;/p&gt;

&lt;p&gt;as node don't have the window object we have to use the Buffer.from function to decode the string&lt;/p&gt;

&lt;p&gt;finally match the input you got from the request with the server secret&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt; if(name===credentials.secretName &amp;amp;&amp;amp; password===credentials.secretPassword){
        // The User is authenticated

        return next()
    }
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;modify your fetch method to write the document when the request is finally successful&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt; .then((response)=&amp;gt;{
                   console.log(response)
                   if(response.status == 200){
                       document.write("SUCCESFULL LOGIN")
                   }
               })
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;let's try out our app in the browser &lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fd665tlrvexnsrxnzyue4.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fd665tlrvexnsrxnzyue4.png" alt="image" width="581" height="38"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;&lt;em&gt;I have provided the inputs with correct secrets let's submit the form&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fgmim00f2oa2zqfwrcibm.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fgmim00f2oa2zqfwrcibm.png" alt="image" width="184" height="33"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Hurray!!!! We are now authenticated by the server and now can access the restricted area&lt;/strong&gt;&lt;/p&gt;

&lt;blockquote&gt;
&lt;p&gt;:PS&lt;br&gt;
There are some caveats in our application such as splitting the &amp;gt;string using ":" delimiter will cause unexpected reaction if the &amp;gt;password or username too have a colon you can fix this by &amp;gt;extracting the username and password by REGEX &lt;/p&gt;

&lt;p&gt;you can improve this application by issuing a bearer token and &amp;gt;storing it in cookie to access across pages and maintain the &amp;gt;login state but that's the story of another day :)&lt;/p&gt;

&lt;p&gt;further reading&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;&lt;a href="https://developer.mozilla.org/en-US/docs/Web/HTTP/Cookies" rel="noopener noreferrer"&gt;https://developer.mozilla.org/en-US/docs/Web/HTTP/Cookies&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;&lt;a href="https://medium.com/@dckalubowila25132/jwt-bearer-token-authentication-for-express-js-5e95bf4dead0" rel="noopener noreferrer"&gt;https://medium.com/@dckalubowila25132/jwt-bearer-token-authentication-for-express-js-5e95bf4dead0&lt;/a&gt;&lt;/p&gt;

</description>
      <category>javascript</category>
      <category>basicauthentication</category>
      <category>tutorial</category>
    </item>
  </channel>
</rss>
