<?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 Mujtaba Hassan on Medium]]></title>
        <description><![CDATA[Stories by Mujtaba Hassan on Medium]]></description>
        <link>https://medium.com/@mujhassan786?source=rss-728c52a2e714------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*sCARDfKF_vAnFYdKRj_n_g.jpeg</url>
            <title>Stories by Mujtaba Hassan on Medium</title>
            <link>https://medium.com/@mujhassan786?source=rss-728c52a2e714------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Wed, 02 Dec 2026 06:38:12 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@mujhassan786/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[Microservices Communication with AWS RabbitMQ and Node.js: A Step-by-Step Guide]]></title>
            <link>https://medium.com/@mujhassan786/microservices-communication-with-aws-rabbitmq-and-node-js-a-step-by-step-guide-76c5ca5e98f7?source=rss-728c52a2e714------2</link>
            <guid isPermaLink="false">https://medium.com/p/76c5ca5e98f7</guid>
            <category><![CDATA[nodejs]]></category>
            <category><![CDATA[rabbitmq]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[microservices]]></category>
            <category><![CDATA[messaging-queue]]></category>
            <dc:creator><![CDATA[Mujtaba Hassan]]></dc:creator>
            <pubDate>Sun, 15 Sep 2024 03:26:00 GMT</pubDate>
            <atom:updated>2024-09-17T11:08:28.876Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6KUX0Y-iYI2vZL2ZaJGKrQ.png" /></figure><p>In this article you will learn how to set up AWS RabbitMQ and use it inside your node application to send and receive messages. I’ll assume you’re somewhat familiar with Node.js and have a little bit of knowledge around microservies architecture.</p><h3>What is RabbitMQ and Why Should You Use It?</h3><p>RabbitMQ is a highly reliable and versatile message broker that allows applications to communicate asynchronously by sending and receiving messages. It functions as an intermediary that helps decouple services in distributed systems, offering a robust and scalable messaging solution for various applications.</p><h3>How RabbitMQ Fits into Microservices Architecture</h3><p>Microservices have become a go-to approach for modern software development because they make it easier to build scalable, maintainable applications. But to work well, microservices need a reliable way to communicate with each other, and that’s where RabbitMQ comes in.</p><p>In a microservices setup, RabbitMQ plays a key role by offering:</p><ul><li><strong>Asynchronous Communication</strong>: Microservices can send messages without waiting for an immediate response, which speeds things up and reduces delays.</li><li><strong>Scalability</strong>: RabbitMQ can handle large volumes of messages and efficiently spread tasks across different microservices.</li><li><strong>Decoupling Services</strong>: RabbitMQ reduces the dependency between services, making each microservice more independent and easier to update or maintain.</li><li><strong>Fault Tolerance</strong>: If one service goes down, RabbitMQ holds onto messages in a queue until that service is back up, ensuring nothing gets lost.</li></ul><p>With RabbitMQ, developers can focus on building microservices that are loosely connected, highly scalable, and more resilient to failures — everything you want in a solid micros\ervices architecture.</p><h3>Setting up AWS RabbitMQ</h3><p>Log into your AWS account and search for amazon MQ</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Qia6cFNetoILJKDyGsbaMw.png" /></figure><p>After that click on the Amazon MQ service and then click on the get started button under create brokers.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*t24X_nwPa4IdUutMebVsTQ.png" /></figure><p>Select the RabbitMQ option.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*BwsETJPuAeo6eO4_72ONIw.png" /></figure><p>Select single instance broker for demo purpose, in production cluster mode will make more sense.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1vMu7jPXP-nOHtaFC_ZTJA.png" /></figure><p>Give the broker a name, select an instance type and more importantly add username and password. Do remember these username and password as they will be used latter.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*iNOAgv_KZLUP2THSPrSyXw.png" /></figure><p>After the above step go to the next step and press create broker.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_yq6bJ6qhYkmQ1UR-SSXjQ.png" /></figure><p>A broker creation takes some time so you would need to wait a little. After the creation is done and the broker is in running form, open the broker details and get the connection details.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*NCyGFb9tfi_iayPAJowXuw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*JVCwSBOj6zkWOIa5XWkSGA.png" /></figure><p>After you are done setting up the broker. Copy the username, password and AMQP endpoint values to the env file.</p><pre>RABBIT_MQ_USERNAME=<br>RABBIT_MQ_PASSWORD=<br>RABBIT_MQ_URL=amqps://b-*******-****-****-****-************.mq.us-east-1.amazonaws.com:5671</pre><h3>Set up the node.js application</h3><p>For demoing purposes you can set up a very basic node.js application. And here is how the rabbitMQ code might look:</p><p>rabbitMQConnectionManager.js file :</p><pre>import amqplib from &quot;amqplib&quot;;<br>import &quot;dotenv/config&quot;;<br><br>let connection = null;<br><br>async function connectToRabbitMQ() {<br>    if (!connection) {<br>        try {<br>            const opt = {<br>                credentials: amqplib.credentials.plain(process.env.RABBIT_MQ_USERNAME,process.env.RABBIT_MQ_PASSWORD)<br>            };<br>            connection = await amqplib.connect(process.env.RABBIT_MQ_URL, opt);<br>            console.log(&quot;Connected to RabbitMQ successfully!&quot;);<br>        } catch (error) {<br>            console.error(&quot;RabbitMQ connection error:&quot;, error);<br>            throw error;<br>        }<br>    }<br>    return connection;<br>}<br><br>export default connectToRabbitMQ;</pre><p>publisher.js file:</p><pre>import connectToRabbitMQ from &#39;./rabbitMQConnectionManager.js&#39;;<br>import { v4 as uuidv4 } from &#39;uuid&#39;;<br><br>async function publishToQueue(queue, payload) {<br>    try {<br>        const connection = await connectToRabbitMQ();<br>        const channel = await connection.createChannel();<br>        await channel.assertQueue(queue);<br>        const correlationId = uuidv4();<br>        payload.correlationId = correlationId<br>        channel.sendToQueue(queue, Buffer.from(JSON.stringify(payload)));<br>        console.log(`Sent &#39;${JSON.stringify(payload)}&#39; to ${queue} with correlationID ${correlationId}`);<br>        await channel.close();<br>        return correlationId<br>    } catch (error) {<br>        console.error(&quot;RabbitMQ publish error:&quot;, error);<br>        throw error;<br>    }<br>}<br><br>export { publishToQueue };</pre><p>receiver.js file:</p><pre>import connectToRabbitMQ from &#39;./rabbitMQConnectionManager.js&#39;;<br><br>async function consumeFromQueue(queue, onMessage) {<br>    const connection = await connectToRabbitMQ();<br>    const channel = await connection.createChannel();<br>    await channel.assertQueue(queue);<br>    console.log(`Waiting for messages in ${queue}.`);<br><br>    channel.consume(queue, (msg) =&gt; {<br>        if (msg !== null) {<br>            const receivedData = JSON.parse(msg.content.toString());<br>            onMessage(receivedData);<br>            channel.ack(msg);<br>        }<br>    }, { noAck: false });<br>}<br><br>export { consumeFromQueue };</pre><p>Here are some brief descriptions of what is happening the above code snippets:</p><p><strong>RabbitMQ Connection Manager</strong>:</p><p>This code establishes and maintains a connection to RabbitMQ using credentials stored in environment variables. It implements the <strong>Singleton design pattern</strong>, ensuring that only a single connection to RabbitMQ is created throughout the application’s lifecycle. If the connection does not exist, it creates one and if the connection already exists, it reuses the existing one, preventing the overhead of repeatedly establishing new connections.</p><p><strong>Publish to RabbitMQ Queue</strong>:</p><p>This function publishes messages to a specified RabbitMQ queue. It first connects to RabbitMQ and creates a <strong>channel</strong>. You may ask what a channel is ?A channel is like a virtual connection inside the main RabbitMQ connection. Instead of opening a new connection every time you send a message (which would be inefficient), RabbitMQ lets you create multiple channels over a single connection. This helps reduce the overhead of managing multiple connections while still allowing you to send and receive messages.</p><p>Once the channel is created, the function asserts the queue (meaning it checks if the queue with the provided name exists, if not it creates a new one), and sends a message with a generated correlationId.<br>The channel is closed after the message is sent to free up resources, ensuring that system performance is optimised and the correlationId is returned. The correlationId comes in handy when tracking a response to an action, just for demoing and understanding how Rabbit MQ works, you can ignore it.</p><p><strong>Consume from RabbitMQ Queue</strong>:</p><p>This function continuously listens for messages from a specified RabbitMQ queue. It creates a channel, asserts the queue, and processes each received message by invoking a callback function (onMessage). The message is acknowledged after processing.</p><p><strong>Example</strong> <strong>Overview:</strong></p><p>In this example, I’ve set up two services, one running on port 3000 and the other on port 3001. The service on port 3000 is responsible for sending a message to a RabbitMQ queue called &#39;task_queue&#39;, while the service on port 3001 listens for and consumes messages from that queue.</p><p>I’ve built a minimal Node.js application to simulate this message-sending and consuming process. In the application running on port 3000, there’s a simple API with a single endpoint. When this endpoint is triggered, it uses the publishToQueue function to send a message to RabbitMQ. Meanwhile, the service on port 3001 consumes the messages being published in the task_queue, using the consumeFromQueue function to process the message.</p><p>This setup demonstrates basic message queuing and asynchronous communication between services using RabbitMQ in a Node.js environment.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/640/1*mHqvpXpE7_XbpdjhW3pPfQ.gif" /></figure><p>Note: To simulate having two separate services, I created a single app in the Git repository and made a copy of it. In one of the copies (for the service running on port 3000), I commented out the message-consuming code so that messages are only consumed by the other service (running on port 3001).</p><p><strong>Git repo:</strong></p><p><a href="https://github.com/Mujtaba52/aws-rabbitmq-node-demo">GitHub - Mujtaba52/aws-rabbitmq-node-demo</a></p><p>If you 🫵 found the article helpful, <strong>👏 </strong>and if you think the code was helpful too, a ⭐️ will be appreciated.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=76c5ca5e98f7" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[SSO Login in Node.js]]></title>
            <link>https://medium.com/@mujhassan786/sso-login-in-node-js-d071b2e4f47d?source=rss-728c52a2e714------2</link>
            <guid isPermaLink="false">https://medium.com/p/d071b2e4f47d</guid>
            <category><![CDATA[okta]]></category>
            <category><![CDATA[single-sign-on]]></category>
            <category><![CDATA[nodejs]]></category>
            <category><![CDATA[aml]]></category>
            <category><![CDATA[sso]]></category>
            <dc:creator><![CDATA[Mujtaba Hassan]]></dc:creator>
            <pubDate>Tue, 20 Aug 2024 14:39:43 GMT</pubDate>
            <atom:updated>2024-08-20T14:39:43.490Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="Single Sign-on" src="https://cdn-images-1.medium.com/max/1024/1*B71YW2DucDXEzIV17Xw04Q.jpeg" /><figcaption>Signal Sign-on</figcaption></figure><h3>SSO Login in Node.js made easy: A Comprehensive Guide to User Authentication with SAML and Leading IdPs like Okta, Auth0, and More</h3><p>In this article, you’ll learn how to integrate any Identity Provider (IdP) with your Node.js application. Unlike many guides that focus on a specific IdP, we’ll develop a generic approach that enables your app to work with any IdP. This guide is particularly useful for <strong>multi-tenant applications</strong>, where your app is designed to serve multiple organizations or clients, each potentially using a different Identity Provider (IdP). While we’ll use Okta as our example, the same principles can be applied to integrate other IdPs seamlessly.</p><p>I’ll assume you’re somewhat familiar with Node.js, Single Sign-On (SSO), and SAML. To briefly recap, SSO is an authentication process that allows users to access multiple applications or services with a single set of credentials, with SAML serving as the standard protocol that securely exchanges authentication information. Once authenticated, users can seamlessly navigate between services without needing to log in again. Below are the straightforward steps to set up Okta integration with your Node.js app.</p><h4>Set up an okta account and application</h4><p>Go to <a href="https://developer.okta.com/">https://developer.okta.com/ </a>and register a developer account.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6MBpse-t-ZyVVsC-S9pmRw.png" /></figure><p>After registering your account go to applications and select create App Integration.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*tZiRBf_uEf2AyeKbLVlgMQ.png" /></figure><p>Select SAML 2.0 as the sign-in method.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*T0Pg-UtiV_jHMAgraYpvDw.png" /></figure><h4>Configure Application</h4><p>Since we are doing this for learning purposes, we’ll use the local Node.js app URL http://localhost:4000. The <strong>Single Sign-On URL</strong> is set to http://localhost:4000/auth/sso-callback?domainName=test_org, where Okta sends the SAML assertion after login, the domainName is included in the URL to identify which organization&#39;s SSO configuration should be used during the callback. The <strong>Audience URI (SP Entity ID)</strong> is also set to http://localhost:4000, acting as a unique identifier to ensure the SAML response is intended for your application. The <strong>Default RelayState</strong> is left blank, so users are redirected to the default landing page after login. These settings ensure that the SAML assertion is securely delivered and properly handled by your application.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Yp2IajEGbPQeFZFnnaX6Bg.png" /></figure><h4>What Are SAML Assertions?</h4><p>SAML assertions are XML documents that contain the authentication information about a user, issued by the Identity Provider (IdP) after successful login. These assertions include details like the user’s identity and are sent to the Service Provider (SP), in this case, your Node.js app, to confirm that the user is authenticated. The SP then validates the assertion, ensuring it’s intended for them and proceeds with granting access to the user.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*yB3p7VzBOiFMm0N-aDCzmw.png" /></figure><p>Once you’ve completed the feedback step, navigate to the <strong>Sign On</strong> tab. Here, you’ll find the settings needed for our integration. We’ll be using the @node-saml/node-saml package to implement our solution. The key parameters you’ll need are:</p><ul><li><strong>issuer:</strong> The unique identifier for the Identity Provider (Okta), ensuring the SAML assertion is issued by the correct IdP.</li><li><strong>audience:</strong> The intended recipient of the SAML assertion, matching your application’s SP Entity ID, to confirm it’s meant for your Node.js app.</li><li><strong>entryPoint (sign on URL):</strong> The URL where the SAML authentication request is sent, directing users to the IdP’s login page (Okta) to initiate SSO.</li><li><strong>callbackUrl:</strong> The endpoint in your app where Okta sends the SAML response after login, handling and validating the assertion.</li><li><strong>wantAuthnResponseSigned:</strong> Specifies whether the SAML response should be signed by the IdP. Set to false here, meaning a signed response isn’t required.</li><li><strong>idpCert:</strong> The public certificate from Okta used to verify the authenticity and integrity of the SAML response.</li></ul><pre>{<br>    &quot;issuer&quot;: &quot;http://www.okta.com/xxxxxxxxxx&quot;,<br>    &quot;audience&quot;: &quot;http://localhost:4000&quot;,<br>    &quot;entryPoint&quot;: &quot;https://dev-xxxxxxx.okta.com/app/xxxxxxx/xxxxxxxxx/sso/saml&quot;,<br>    &quot;callbackUrl&quot;: &quot;http://localhost:4000/auth/sso-callback&quot;,<br>    &quot;wantAuthnResponseSigned&quot;: false,<br>    &quot;idpCert&quot;: &quot;xxxxx&quot;<br>}</pre><p>You can get the above required parameters from the sign on tab.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*dbDRKtmWKbhBv0QzQYCXlA.png" /></figure><p>Assign people to the app.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*gHauyK0YgoxR57vmOCkBnQ.png" /></figure><h4>Set up the node.js application</h4><p>Next, set up a basic Node.js application or integrate this into your existing application. You’ll need to add two new endpoints:</p><ol><li><strong>/sso-login (GET)</strong>: This endpoint initiates the SSO process. It retrieves the organization&#39;s SSO configuration based on the provided domainName and generates a login URL, which is then sent back to the client.</li><li><strong>/sso-callback (POST)</strong>: This endpoint handles the SSO callback. After the user successfully logs in via the Identity Provider (IdP), the SAML response is sent to this endpoint. It validates the SAML assertion, verifies the user, generates an access token, and then redirects the user to the dashboard with the token.</li></ol><p>Here how the code for these endpoints look<strong>:</strong></p><pre>const ssoLogin = async (req, res)=&gt;{<br>    let { domainName } = req.query;<br>    const organization = await organizations.findOne({domainName})<br><br>    if(!organization) return res.status(404).json({ message: &quot;No organization found&quot; });<br>    const { ssoConfig } = organization;<br>    const loginUrl = await getLoginUrl(ssoConfig);<br>    res.json({ ssoUrl: loginUrl });<br>  }<br><br>async function ssoCallback(req, res) {<br>    try {<br>      let { domainName } = req.query;<br>      const organization = await organizations.findOne({domainName})<br><br>      if(!organization) throw boom.notFound(&#39;Organization Not found&#39;);<br>      const assertion = await validateLogin(req.body, organization.ssoConfig);<br>      const email = assertion.nameID<br>      if (!email) throw boom.unauthorized(&#39;Email not found in SAML assertion.&#39;);<br>      const ssoUser = await user.findOne({ email });<br><br>      if (!ssoUser) { throw boom.unauthorized(&#39;SSO login was attempt was failed.&#39;) }<br>      const userAccessToken = generateAccessToken(ssoUser._id.toString());<br>      //redirect to dashboard with the token in the url.<br>      res.redirect(`${process.env.DASHBOARD_URL}?token=${userAccessToken}`);<br>    } catch (error) {<br>      res.status(500).json({ message: error.message });<br>    }<br>  }</pre><p>Here are utils functions being used:</p><pre>import { SAML } from &quot;@node-saml/node-saml&quot;;<br>import &quot;dotenv/config&quot;;<br>import jwt from &#39;jsonwebtoken&#39;;<br><br>async function getLoginUrl(samlOptions) {<br>    const saml = new SAML(samlOptions);<br>    const loginUrl = await saml.getAuthorizeUrlAsync();<br>    return loginUrl;<br>};<br><br>async function validateLogin(samlResponse, samlOptions) {<br>    const saml = new SAML(samlOptions);<br>    const response = await saml.validatePostResponseAsync(samlResponse);<br>    return response.profile;<br>  };<br><br>  const generateAccessToken = id=&gt; jwt.sign({ id }, process.env.JWT_SECRET, { expiresIn: &#39;24h&#39; });</pre><p>In the above code the SAML class acts as a toolkit for handling SAML requests and responses in Single Sign-On (SSO). By passing samlOptions, you configure this toolkit with the necessary settings to interact with the Identity Provider (IdP) like Okta. The getAuthorizeUrlAsync method generates a secure login URL that directs the user to the IdP’s login page. After the user logs in, the validatePostResponseAsync method uses the toolkit to validate the SAML response (samlResponse) received from the IdP, ensuring the response is legitimate and extracting the user’s information.</p><h4>Workflow Overview</h4><p>When you navigate to http://localhost:4000/auth/sso-login?domainName=test_org, the application retrieves the corresponding SSO configuration for the organization based on the domain name provided. The server then generates a SAML authentication request and returns an ssoUrl. The frontend uses this URL to redirect the user to the organization’s Identity Provider (IdP), such as Okta, where they enter their credentials.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*19UtR1uYtpsnanzpem1a-Q.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*yjBn8WYYE0M3wTM3n_LMjw.png" /></figure><p>After a successful login, Okta will redirect the user to the Single Sign-On URL you configured, which in this case is http://localhost:4000/auth/sso-callback?domainName=test_org. The application will then validate the SAML response, generate a JWT token, and redirect the user to the dashboard URL, in this case http://localhost:3000, with the token included in the URL. The frontend can now use this JWT token to authenticate the user and maintain their session.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*fWMZ64fYkAEjxBhDSqFX8Q.png" /></figure><h4>Git repo:</h4><p><a href="https://github.com/Mujtaba52/sso-app-backend">GitHub - Mujtaba52/sso-app-backend</a></p><p>If you 🫵 found the article helpful, <strong>👏 </strong>and if you think the code was helpful too, a ⭐️ will be appreciated.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d071b2e4f47d" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>