<?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 Sukitha Jayasinghe on Medium]]></title>
        <description><![CDATA[Stories by Sukitha Jayasinghe on Medium]]></description>
        <link>https://medium.com/@sukithaj?source=rss-49dd67ef6d69------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*VrIYdX_GPF-3zOJzoy1wEQ.jpeg</url>
            <title>Stories by Sukitha Jayasinghe on Medium</title>
            <link>https://medium.com/@sukithaj?source=rss-49dd67ef6d69------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 01 Dec 2026 00:15:11 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@sukithaj/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[Realtime Audio transcription with AWS Transcribe, Nodejs, and Gstreamer]]></title>
            <link>https://sukithaj.medium.com/realtime-audio-transcription-with-aws-transcribe-nodejs-and-gstreamer-8e069f58f854?source=rss-49dd67ef6d69------2</link>
            <guid isPermaLink="false">https://medium.com/p/8e069f58f854</guid>
            <category><![CDATA[gstreamer]]></category>
            <category><![CDATA[nlp]]></category>
            <category><![CDATA[nodejs]]></category>
            <category><![CDATA[aws]]></category>
            <category><![CDATA[cloud-computing]]></category>
            <dc:creator><![CDATA[Sukitha Jayasinghe]]></dc:creator>
            <pubDate>Sun, 30 Jan 2022 07:15:57 GMT</pubDate>
            <atom:updated>2022-01-30T13:25:56.501Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xbMHhjPsGUyLHVg_ApTdOw.jpeg" /></figure><p>Transcribe is a machine learning service provided by AWS that is used for converting speech to text. This service is built on top of <a href="https://en.wikipedia.org/wiki/Speech_recognition">ASR (Automatic Speech Recognition)</a> and <a href="https://en.wikipedia.org/wiki/Natural_language_processing#:~:text=Natural%20language%20processing%20(NLP)%20is,amounts%20of%20natural%20language%20data.">NLP (Natural Language Processing)</a> technologies. Transcribe provides easy-to-read transcripts by providing features such as punctuation, number normalization, time gap generation, and multiple speaker recognition.</p><p>Realtime Audio Transcription is one of the coolest features that allow streaming Audio and reading Text from a Websocket. In this article, I am going to show how to build a nodejs application to stream an audio file and print the text output.</p><h4>Design</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/431/1*xGDF6rWGPfQcI_3VBroFpw.jpeg" /></figure><p>Gstreamer pipeline mimics the audio streaming service that loads a sample mp3 file using <em>filesrc</em> and streams it to Nodejs TCP Server using <em>tcpclientsink </em>plugin<em>. </em>Nodejs TCP Server reads these audio chunks, converts them to binary messages, and finally forwards them to the Transcribe through a WebSocket. Then it reads the result and output to the shell.</p><h4>Gstreamer</h4><pre>gst-launch-1.0 filesrc location=&quot;/home/ubuntu/NSC_.mp3&quot; ! decodebin ! audioconvert ! audioresample ! audio/x-raw, rate=16000 ! flacenc ! tcpclientsink port=2225</pre><p>Gstreamer pipeline reads the file from the source, converts to a suitable audio format, and streams it to the TCP port.</p><h4>Nodejs Application</h4><p>AWS has provided a content-rich <a href="https://docs.aws.amazon.com/transcribe/latest/dg/streaming.html">guide </a>that explains steps on how to use the WebSocket interface to access Transcribe functionality.</p><p>First We need to create a nodejs TCP server to listen to port 2225 and read audio streaming from Gstreamer. We can use the “net” package provided by nodejs for this purpose.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d258f8daeb73926a853148d05c9a4e4d/href">https://medium.com/media/d258f8daeb73926a853148d05c9a4e4d/href</a></iframe><p>Then we need to create a method to convert audio chunks to transcribe stream API-friendly binary messages. Set of utility methods provided by AWS Javascript SDK to achieve this.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/479931cd75d3a8a06c7fe54af56423a6/href">https://medium.com/media/479931cd75d3a8a06c7fe54af56423a6/href</a></iframe><p>Now receiving and converting the audio chunk part is completed. Next is the most important part, Stream the converted binary messages to Transcribe through a WebSocket. The first step is connecting the Transcribe using WebSocket which is protected by Amazon Signature Version 4 signing method. There are enough code samples available on the web that explain the signing process. I copied the code directly from this <a href="https://github.com/amazon-archives/amazon-transcribe-websocket-static/blob/master/lib/aws-signature-v4.js">link</a> and modified it a little bit.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/9820d9422efd7a440285a544d76748ff/href">https://medium.com/media/9820d9422efd7a440285a544d76748ff/href</a></iframe><p>Now we can use the above code to generate the pre-signed URL to connect to Transcribe service.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/1335aba62f899c1a7fc181368947702b/href">https://medium.com/media/1335aba62f899c1a7fc181368947702b/href</a></iframe><p>Finally, read the results from the WebSocket and output to the shell. A result is a JSON object that contains lots of details. One of the most important among them is <em>IsPartial. </em>Because this is a streaming service, the socket starts returning results as soon as it starts streaming the audio. Transcribe provides two types of result sets, partial and completed. It returns incremental partial results until it identifies the pause of the audio using the NLP engine. Then the final result will be generated and forwarded.</p><pre>{<br>  &quot;TranscriptResultStream&quot;: {<br>    &quot;TranscriptEvent&quot;: {<br>      &quot;Transcript&quot;: {<br>        &quot;Results&quot;: [<br>          {<br>            &quot;Alternatives&quot;: [<br>              {<br>                &quot;Items&quot;: [<br>                  {<br>                    &quot;Content&quot;: &quot;The&quot;,<br>                    &quot;EndTime&quot;: 0.3799375,<br>                    &quot;StartTime&quot;: 0.0299375,<br>                    &quot;Type&quot;: &quot;pronunciation&quot;,<br>                    &quot;VocabularyFilterMatch&quot;: false<br>                  },<br>                  {<br>                    &quot;Content&quot;: &quot;Amazon&quot;,<br>                    &quot;EndTime&quot;: 0.5899375,<br>                    &quot;StartTime&quot;: 0.3899375,<br>                    &quot;Type&quot;: &quot;pronunciation&quot;,<br>                    &quot;VocabularyFilterMatch&quot;: false<br>                  },<br>                  {<br>                    &quot;Content&quot;: &quot;is&quot;,<br>                    &quot;EndTime&quot;: 0.7899375,<br>                    &quot;StartTime&quot;: 0.5999375,<br>                    &quot;Type&quot;: &quot;pronunciation&quot;,<br>                    &quot;VocabularyFilterMatch&quot;: false<br>                  },<br>                  {<br>                    &quot;Content&quot;: &quot;the&quot;,<br>                    &quot;EndTime&quot;: 0.9199375,<br>                    &quot;StartTime&quot;: 0.7999375,<br>                    &quot;Type&quot;: &quot;pronunciation&quot;,<br>                    &quot;VocabularyFilterMatch&quot;: false<br>                  },<br>                  {<br>                    &quot;Content&quot;: &quot;largest&quot;,<br>                    &quot;EndTime&quot;: 1.0199375,<br>                    &quot;StartTime&quot;: 0.9299375,<br>                    &quot;Type&quot;: &quot;pronunciation&quot;,<br>                    &quot;VocabularyFilterMatch&quot;: false<br>                  }<br>                ],<br>                &quot;Transcript&quot;: &quot;The Amazon is the largest&quot;<br>              }<br>            ],<br>            &quot;EndTime&quot;: 1.02,<br>            &quot;IsPartial&quot;: true,<br>            &quot;ResultId&quot;: &quot;2db76dc8-d728-11e8-9f8b-f2801f1b9fd1&quot;,<br>            &quot;StartTime&quot;: 0.0199375<br>          }<br>        ]<br>      }<br>    }<br>  }<br>}</pre><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/09b8759a868ba795b290f558fdf15ffd/href">https://medium.com/media/09b8759a868ba795b290f558fdf15ffd/href</a></iframe><p>Now our code is ready. Time to test the solution.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*lce_5BZtD-IUhV2UbkCyQQ.gif" /></figure><h4>Conclusion</h4><p>There are varieties of use cases available for real-time transcription. Some of these use cases of real-time transcription are call centers and Broadcasting services. These transcriptions can be fed into AI systems and identify events that can trigger downstream actions such as sending alerts to call center supervisors. Further, they can be fed into search platforms to build knowledge bases. There are services like AWS Comprehend which can extract valuable information from transcripts for further processing.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8e069f58f854" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Distributed Transaction — Implementation using REDIS and NodeJS]]></title>
            <link>https://sukithaj.medium.com/distributed-transaction-implementation-using-redis-and-nodejs-c27c00328e4a?source=rss-49dd67ef6d69------2</link>
            <guid isPermaLink="false">https://medium.com/p/c27c00328e4a</guid>
            <category><![CDATA[microservice-architecture]]></category>
            <category><![CDATA[nodejs]]></category>
            <category><![CDATA[microservices]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[redis]]></category>
            <dc:creator><![CDATA[Sukitha Jayasinghe]]></dc:creator>
            <pubDate>Sat, 02 Oct 2021 11:30:12 GMT</pubDate>
            <atom:updated>2021-10-03T11:34:52.673Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Pk4X9TsBud4RVFfZtUfKnQ.png" /></figure><h3>Distributed Transaction — Implementation using REDIS and NodeJS</h3><p>The distributed transaction implementation has become one of the biggest challenges in microservice development due to its distributed nature. There are some well-known patterns available to address this problem. In this article, I am going to explain a sample implementation done using Redis and Nodejs. First of all, let&#39;s discuss the background of the problem which we are going to solve.</p><p>In design, RDBMS systems support ACID transactions. Transactions revert themselves if any statement gets failed. The Microservice model doesn&#39;t support this because of the dedicated datastore available for service. Most of these datastores behave according to the BASE properties. You can read more about ACID vs BASE from this article (<a href="https://phoenixnap.com/kb/acid-vs-base">Link</a>).</p><p>It is important to understand a complete ACID transaction is not possible in the microservice model. Hence your distributed transaction implementation is highly subjective to the problem domain and expectation of the system. I have made some assumptions when implementing this sample.</p><p>Let&#39;s see the component design of the solution first.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/786/1*6WZExk-r0J7QgFadcK5yyw.png" /><figcaption>Successful Transaction</figcaption></figure><h4>Components</h4><ul><li>REST Service</li><li>Order Service</li><li>Payment Service</li><li>Delivery Service</li><li>Status Service</li></ul><h4>REST Service</h4><p>The REST service is the entry point. It accepts and validates the request before generating an id for the transaction. The generated id returns to the client in the http response. Validated request forwards to the <em>ORDER: QUEUE </em>for further processing.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/6bf66b3609ae3209b147c4712c1b8081/href">https://medium.com/media/6bf66b3609ae3209b147c4712c1b8081/href</a></iframe><h4>REST Service Request and Response</h4><p>Data get stored in an Eventual consistent manner so anytime we can replay the transaction and do manual or batch reconciliation on failure.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*odJZBVlrqwFvRxRxJFhnBA.png" /><figcaption>Post Request to create an Order</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*tARrdas7wtjXA6jpN9dlrg.png" /><figcaption>Get Request to Poll the transaction status</figcaption></figure><h4>Order Service/Payment/Delivery Services</h4><p>Each Service reads the request, processes it further, and embeds additional details such as cost. Then forwards the event to the next queue. The reconciliation process is also implemented in the same service. So the responsibility of reversing the transaction is given to the relevant service.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/2a295754ae56952504e785b2d0065116/href">https://medium.com/media/2a295754ae56952504e785b2d0065116/href</a></iframe><h4>Recovery</h4><p>Let&#39;s look at the reconciliation process.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/756/1*eiLDQ2R2pmekE4OvvB2Zpw.png" /></figure><p>The diagram shows how the recovery process gets executed when the payment operation fails. I have simulated this by setting item id 200 as a failure case. In this scenario, the payment service informs the Order service to revert the transaction. Order service changes the soft status to failure. The front end can see that transaction failed. There are some best practices when designing reversing transactions. The reverse process should be simple and it shouldn&#39;t fail easily. Irreversible steps such as send SMS should execute at end of the transaction.</p><h4>Conclution</h4><p>The implementation done in this article is very simple. The actual problem domains are much more complex and may involve dozens of services and hundreds of events. But the basic concepts remain the same. There are lots of technologies and concepts that can help to solve similar issues (<a href="https://developers.redhat.com/blog/2018/10/01/patterns-for-distributed-transactions-within-a-microservices-architecture">Link</a>).</p><p>I have used Redis as the queue in this sample. But, Kafka might be a better queue selection for production as we can use <em>Kafka ack</em> to implement application-level fault tolerance, <em>Kafka Connect</em> with Debezium as CDC solution and Kafka itself as the event sourcing database.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c27c00328e4a" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Distributed Task Scheduler — Redis]]></title>
            <link>https://sukithaj.medium.com/distributed-task-scheduler-redis-329475df9dcf?source=rss-49dd67ef6d69------2</link>
            <guid isPermaLink="false">https://medium.com/p/329475df9dcf</guid>
            <category><![CDATA[redis]]></category>
            <category><![CDATA[microservices]]></category>
            <category><![CDATA[nodejs]]></category>
            <category><![CDATA[programming]]></category>
            <dc:creator><![CDATA[Sukitha Jayasinghe]]></dc:creator>
            <pubDate>Sat, 27 Mar 2021 09:26:15 GMT</pubDate>
            <atom:updated>2021-03-28T01:42:02.227Z</atom:updated>
            <content:encoded><![CDATA[<h3>Distributed Task Scheduler — Redis</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6Ji_bz2-eFljLbf6aOt9bQ.jpeg" /></figure><p>Redis has become an essential component in distributed microservice application domain due to its simplicity, performance, and clean set of features. This article is about building a task scheduling system using some of the Redis features. The requirement is selected as below for the sake of defining the boundary and way of explaining.</p><h3>Requirement:</h3><ul><li>The system has to be scalable and distributed</li><li>Multiple worker processes</li><li>Tasks can be real-time or delayed</li><li>The resource consumption should be minimum when idle</li></ul><h3>Design</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/791/1*4QijUwRApW3Yjd2KmanY3Q.jpeg" /><figcaption>Task Scheduling System — Block Diagram</figcaption></figure><p>The system consists of four <strong>components</strong></p><ul><li>Task API: Task producer</li><li>REDIS: A distributed data structure that has SORTED SET and FIFO supported LIST</li><li>Task Scheduler: Read tasks and push them to the LIST in precise time</li><li>Task Worker: Task consumer</li></ul><h4>The Steps:</h4><ol><li>Task API calculates the score and adds task items to the ZSET with the score</li><li>Task Scheduler keeps checking the first item of the set.</li><li>The Item will push to the worker queue if the score matches the current time</li><li>The task worker stays in a blocking queue and executes as soon as an item added to the queue</li></ol><h4>Task API</h4><p>Task API is a <a href="http://restify.com/">restify </a>POST handler that accepts the task and pushes it to Redis based on the “when” property. Each item pushes to the <a href="https://redis.io/commands/ZADD">ZSET </a>will be a JSON encoded array with three items (identifier, worker queue name, and task details). In the ZSET every member is associated with a score, that sorts the set in ascending order. The “when” property is Epoch converted and assigned as the score.</p><pre>async SaveTask(req, res, next) {<br>        let queue = req.params.queue;<br>        let id = uuidV4();<br>        let time = req.body.when;<br>        let item = [id, queue, req.body.task];<br>        let score = 0;<br>        let status = &#39;PENDING&#39;;<br>        if (time) {<br>            score = new Date(time).getTime()<br>            console.log(`Push task ${id} to process later on ${time} `);<br>            await redisHandler.AddToSortedSet(JSON.stringify(item), score);<br>            status = &#39;SCHEDULED&#39;;</pre><pre>} else {<br>            console.log(`Push task ${id} to execute in relatime`);<br>            await redisHandler.AddItemToQueue(queue, JSON.stringify(item));<br>            status = &#39;QUEUED&#39;;<br>        }</pre><pre>res.send({ item: item, score: score, status: status });</pre><pre>}</pre><p><a href="https://github.com/luin/ioredis">ioredis</a> code segment</p><pre>async AddToSortedSet(item, value) {<br>        return new Promise((resolve, reject) =&gt; {<br>            this.redisClient.zadd(`ZSET:SCHEDULED:ITEMS`, value, item, (err, result) =&gt; {<br>                if (err) {<br>                    reject(err);<br>                } else {<br>                    resolve(result);<br>                }<br>            })<br>        })<br>    }</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ZglEETcMUXHDeni5iqSqwg.png" /><figcaption>ZSET values</figcaption></figure><h4>Task Scheduler</h4><p>The task scheduler acquires the lock then processes the critical section. It reads the first item from the ZSET and compares “when” against the current time. The selected task is removed from ZSET and pushes to the relevant queue for processing.</p><pre>async ProcessEvents() {<br>  while (true) {<br>    try {<br>      await lock.acquire(`LOCK:ZSET:ITEMS`);<br>      try {<br>        let value = await redisHandler.GetTopFromSortedSet();<br>        if (value &amp;&amp; value.length &gt; 0) {<br>          let item = JSON.parse(value[0]);<br>          let time = value[1];<br>          if (parseFloat(time) &lt;= Date.now()) {<br>            console.log(`Scheduled item ${item[0]} ready to process`);<br>            await redisHandler.DeleteItemFromSet(value[0]);<br>            await redisHandler.AddItemToQueue(item[1], value[0]);<br>          }<br>        }else {<br>          //No items to work process wait 1s before check again<br>          await lock.release();<br>          await new Promise(r =&gt; setTimeout(r, 1000));<br>          continue;<br>        }<br>      } catch (ex) {<br>        console.log(`Error on event processing ${ex.message}`);<br>      }<br>      await lock.release();<br>    } catch (ex) {<br>      // error in acquiring or releasing the lock<br>    }<br>    await new Promise(r =&gt; setTimeout(r, 100));<br>  }<br>}</pre><p><a href="https://github.com/luin/ioredis">ioredis</a> code segment</p><pre>async GetTopFromSortedSet() {<br>        return new Promise((resolve, reject) =&gt; {</pre><pre>this.redisClient.zrange(`ZSET:SCHEDULED:ITEMS`, 0, 0, &quot;WITHSCORES&quot;, (err, result) =&gt; {<br>                if (err) {<br>                    reject(err);<br>                } else {<br>                    resolve(result);<br>                }<br>            })<br>        })<br>    }</pre><pre>async DeleteItemFromSet(item) {<br>        return new Promise((resolve, reject) =&gt; {</pre><pre>this.redisClient.zrem(`ZSET:SCHEDULED:ITEMS`, item, (err, result) =&gt; {<br>                if (err) {<br>                    reject(err);<br>                } else {<br>                    resolve(result);<br>                }<br>            })<br>        })<br>    }</pre><pre>async AddItemToQueue(key, item) {<br>        return new Promise((resolve, reject) =&gt; {</pre><pre>this.redisClient.rpush(`QUEUE:${key}`, item, (err, result) =&gt; {<br>                if (err) {<br>                    reject(err);<br>                } else {<br>                    resolve(result);<br>                }<br>            })<br>        })<br>    }</pre><h4>Task Processor</h4><p>Task Processor mimics FIFO behavior using blocking left pop (<strong><em>blpop</em></strong>) method. The method releases the process as soon as an item is available on the list. It <strong>requires a dedicated Redis client for blocking operations</strong> as it blocks other Redis operations also.</p><pre>async ProcessTasks(queue) {</pre><pre>while (true) {</pre><pre>let taskArray = await redisHandler.GetItemFromQueueBlocking(queue);<br>            if (taskArray &amp;&amp; taskArray.length &gt; 1) {<br>                let task = JSON.parse(taskArray[1]);<br>                if (task &amp;&amp; Array.isArray(task) &amp;&amp; task.length &gt; 2) {<br>                    let item = task[2];<br>                    console.log(`Task ${task[0]} ready to process - action: ${item.action} params: ${item.time}`);<br>                    await new Promise(r =&gt; setTimeout(r, item.time));<br>                }<br>            }<br>        }</pre><pre>}</pre><p><a href="https://github.com/luin/ioredis">ioredis</a> code segment</p><pre>async GetItemFromQueueBlocking(key) {<br>        return new Promise((resolve, reject) =&gt; {</pre><pre>this.redisClient.blpop(`QUEUE:${key}`, 5000, (err, result) =&gt; {<br>                if (err) {<br>                    reject(err);<br>                } else {<br>                    resolve(result);<br>                }<br>            })<br>        })<br>    }</pre><h3>Discussion</h3><p>Redis is an excellent tool for implementing various distributed patterns in the microservice domain. There are many data structures available to implement these patterns. Some of them are Distributed locks, Publish and Subscriber, Atomic counter for Dashboards, AutoComplete systems using searching. The source can be found on <a href="https://github.com/sukitha/distributed-task-scheduler">git</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=329475df9dcf" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[JWT, JWS and JWE in nodejs]]></title>
            <link>https://sukithaj.medium.com/jwt-jws-and-jwe-in-nodejs-7595542565d0?source=rss-49dd67ef6d69------2</link>
            <guid isPermaLink="false">https://medium.com/p/7595542565d0</guid>
            <category><![CDATA[security]]></category>
            <category><![CDATA[jwt]]></category>
            <category><![CDATA[nodejs]]></category>
            <category><![CDATA[programming]]></category>
            <dc:creator><![CDATA[Sukitha Jayasinghe]]></dc:creator>
            <pubDate>Mon, 22 Mar 2021 02:38:23 GMT</pubDate>
            <atom:updated>2021-03-23T02:00:13.127Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9HB99u7Cq4pBcArZPZ7oEQ.jpeg" /></figure><p>JSON Web Token (JWT pronounced as ‘jot’) is the IETF standard for transmitting JSON format claims between interested parties in a secure and compactable way. JWT has become the open standard for token-based authorization.</p><blockquote><a href="https://tools.ietf.org/html/rfc7519">JSON Web Token (JWT) is a compact, URL-safe means of representing<br> claims to be transferred between two parties. The claims in a JWT<br> are encoded as a JSON object that is used as the payload of a JSON<br> Web Signature (JWS) structure or as the plaintext of a JSON Web<br> Encryption (JWE) structure, enabling the claims to be digitally<br> signed or integrity protected with a Message Authentication Code<br> (MAC) and/or encrypted.</a></blockquote><h4>Properties of JWT</h4><ul><li>Compact</li><li>Claims are JSON encoded</li><li>URL safe (base 64 URL encoded)</li><li>Self-contained (Hence implementing stateless authorization is possible)</li></ul><h4>Authorization using JWT</h4><p>When it comes to authorization there are two main approaches</p><ol><li>Sessionless token-based (JWT)</li><li>Session-based (cookies)</li></ol><p>It is important to understand session-based authorization mechanisms in detail first, to identify the advantage of using sessionless token-based authorization. The session-based authorization method has two parts.</p><ol><li>Server store reference objects against the session-id</li><li>The client has the session (cookie) saved in the application with server details such as domain</li></ol><p>When the client needs to access server resources it sends the session (cookie) with the HTTP requests. The server validates the session to give access to the resources. The server has to read reference objects related to the session further to identify the requester. There are some limitations of this process that are addressed by JWT token-based authorization systems.</p><p><strong>Advantages of Token-based Authorization</strong></p><ul><li>Stateless</li><li>Decentralized authorization (micro-service friendly)</li><li>Hybrid, Single page application friendly</li><li>Mobile application friendly</li><li>Centralized token storage is not required</li></ul><h4>JWT variations</h4><p>The Follow is a sample JWT taken from (https://openid.net/specs/draft-jones-json-web-signature-04.html). This has three parts separated by period (.) which are base64 URL encoded plain text values.</p><blockquote>eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJpc3MiOiJqb2UiLCJleHAiOjEzMDA4MTkzODAsImh0dHA6Ly9leGFtcGxlLmNvbS9pc19yb290Ijp0cnVlfQ.Kd7k33MK6gl5nlSy6-c5xZKvPZBXCF4xl5S6UmWTnsg</blockquote><p>jwt.io is used for decoding this token and inspect the content.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/804/1*ZQaAk4269N5D5Bt8SqY39A.png" /><figcaption>Sample JWT from jwt.io</figcaption></figure><h4>The “Three parts” of the token</h4><p><strong>Header: { “typ”: “JWT”, “alg”: “HS256”}</strong></p><p>The header is known as <strong>JOSE </strong>(Javascript Object Signing and Encryption ) contains information about the sign and/or encryption algorithm the token generated with. The above example is signed using <strong>HS256 </strong>(HMAC with SHA-256), which is a symmetric algorithm.</p><p><strong>Payload:</strong></p><p>The payload contains two types of claims called <em>Registered claims</em> and <em>Custom</em> <em>claims.</em> Registered claims are well defined in the RFC. Some of them are <strong>iss</strong> (issuer), <strong>exp</strong> (expiration time), <strong>sub</strong> (subject), <strong>aud</strong> (audience). More details can be found in the RFC <a href="https://tools.ietf.org/html/rfc7519#section-4.1">document</a><a href="https://tools.ietf.org/html/rfc7519#section-4.1.">.</a> Registered claims can be used as additional validations for the token. Custom claims can be any key/value pairs that can be defined based on the application requirements.</p><p><strong>Signature:</strong></p><p>The signature is created by applying the signing algorithm to the header and payload combination. This prevents modification to the token once released to the client.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/646/1*COcXTo9x9qyWelWppDrXLQ.png" /><figcaption>Signature section from jwt.io</figcaption></figure><h4>JWT variations JWS and JWE</h4><p><strong>JWT </strong>is called <strong>JWS </strong>(JSON Web Signature) when the token is signed as the above example. The <strong>JWS </strong>token has integrity (it is not possible to modify the token without invalidating the signature). The <strong>JWS </strong>token can be decoded easily using a base64 encoder, so it is not a good option to transmit sensitive data. The <strong>JWE </strong>(JSON Web Encryption) comes as the solution to this problem by introducing encryption to the JWT. JWS is the well-known variation of JWT implementation. There are libraries and lots of samples available to verify, decode and generate JWS tokens. Therefore JWE is discussed in detail with sample codes.</p><h4>JWE</h4><p>JWE is the standard way of encrypting claims of the JWT token. The code segments explain how to load keys, encrypt the token, and decrypt the token. These codes are written in node js using the cisco <a href="https://github.com/cisco/node-jose#readme">node-jose</a> library.</p><p>The node-jose library provides a JWK namespace to generate, import, and export keys. In this example, an asymmetric key pair is used to encrypt the payload.</p><p><strong>Key pair is generated using open SSL commands</strong></p><p>openssl genrsa -des3 -out private.pem 2048<br>openssl rsa -in private.pem -outform PEM -pubout -out public.pem<br>openssl rsa -in private.pem -out plain_private.pem</p><p>cat plain_private.pem</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/615/1*o0dQVhgrxeaWW6dH8-q3tg.png" /><figcaption>private key</figcaption></figure><p>cat public.pem</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/609/1*G4e3cbifC8kbdSCQlYAW1w.png" /><figcaption>public key</figcaption></figure><p><strong>Key Importing sample code:</strong></p><pre>const { JWK } = require(&#39;node-jose&#39;);<br>let makeKeys = async () =&gt; {<br>    let privateKey = `-----BEGIN RSA PRIVATE KEY-----<br>MIIEowIBAAKCAQEAwiSxcx5xFsNCjfDTOXz0M6RivgPXTTKb/PH6/x4vYl1xg/vI<br>rG1yDGyFuyAizxNaGtA+qo2CvM3iATyDWQg3/8vDWiD4cIvUD2WE3XXewjyeGzQs<br>o26DceRxopI2tlSgvznjifetGCp+oj4BWrTCqLF1AsR2ioUS7vuXMlpxXFhJfyEG<br>oWuQaZDwoz7CZv1KrQwlRTtkqtn4IeXpVcgWhg/1r0iRsvNJDokyiMVY8hrrvza2<br>j31JGaKYqCNYSC8Jf5EV7ONQhYGgQeRVxn8jS8UhLOFXDdNtgHwKi02tF1bmb3Ko<br>/s3vzPvFB8C7CsYRtHAzcx/xor2/CbT0QGYfUQIDAQABAoIBADgdoQj0UJ3SvKcI<br>aBViz7cpmbzwoUfYDAx16SXalLmq5sfOfDeSvvdmWtU2ubj/D/lWHfbwRkzKebv/<br>wLt4S69tNz8S7pyhXh9BKcFVc5jTKqQUVZ67r9S4wjvKZXQYTApZ8jIL3AVzKv08<br>TOnp+6YE/RxaqyToyAs5v383czLMdSM9bThDw+IZHfKFcl2iyUI4XVaPLDZPzUlG<br>MW13ypwFQXbdro9pnMs9v2573WumIVvbiLqIdxK1anag0KbCnCY2hDmoLNv7Mohz<br>1pFiqEStI6DQsYfEm/geIIL9nLhA8QJ28B9DtLKqRN7oWl2w5BiMEDCrmVK/4niM<br>lsqF1ZECgYEA5zVsjoJzRCBgZ5dRx9BOu9MKXQ+h00LS3+JaApEzW+QV0DplTvb5<br>aRUHhTIhUig2WdQVrEiBVXKg9eYmOBXOpX5pgDO5XJ16KcjdHcwMwoYAcUPIT5Y2<br>tMgoX+jCgTt95cnLKhAnSlH9cCyq+nmcdfDNuvNx8HJO7P33MaVDHCUCgYEA1vXX<br>cBWM+sGkUxpJNwlgA8bO7xq2kpbM3gqa0z6SKQhxnnmPyoKsZSHdwQMUCKIWBLjU<br>n27STmXm2SblT1cT39MCED2t0U7N2D1KUQfZkFaN4gImF77iZBWIfDLObAom6JKg<br>gER0glakAjbDMKq90mVzrKrR6XsD3az+AJE1eL0CgYBbHKB04E9QD3ouGGFv3lTI<br>i3fQCHL676Bt/aL+0/1rPsyhzAFURtsuX80g3gpnd9VDPOJ1i/T7mTp47IMvItjW<br>OqSUks1/A8e6Y59POLPmjCvsdoufYVCZmS7f7LeJeco5HXZkUw1Iqlq3M8MFBZt0<br>lrpb68eAu2sC1WnuNHPnyQKBgQC1LFb7vO4pmnOpJwp2PIyUIkfe9qDSRA8/Rajg<br>Smhd9SPt8X7jq+cpBbYlKzcDX7k3GaD7DyhpszEx7LpweG/jwbCHh7SsKMMNcfrk<br>+LzCDnFe/3ijotqkiBGUvC2GmbfZZVupQAkCoYtx4j35Eq8SWTd5XC+3nVrQxzD9<br>wWVT8QKBgBylVSsVeU7H/RT3RZ/qgWnpllBzGJic8X6lfyTHVD/9dO9XMzuD7R+/<br>VFc9Ib71QPzyq39BX+YiCI+xwDGARgO3GGA4vxvF46Tq0rYUpZ1LiC4raO4I5xrl<br>NxZCLVlhLWU27FR7xu8YN18mRCCwz1FCcsEtNU4nrBK2IIIwGLCf<br>-----END RSA PRIVATE KEY-----`;<br>    let publicKey = `-----BEGIN PUBLIC KEY-----<br>MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAwiSxcx5xFsNCjfDTOXz0<br>M6RivgPXTTKb/PH6/x4vYl1xg/vIrG1yDGyFuyAizxNaGtA+qo2CvM3iATyDWQg3<br>/8vDWiD4cIvUD2WE3XXewjyeGzQso26DceRxopI2tlSgvznjifetGCp+oj4BWrTC<br>qLF1AsR2ioUS7vuXMlpxXFhJfyEGoWuQaZDwoz7CZv1KrQwlRTtkqtn4IeXpVcgW<br>hg/1r0iRsvNJDokyiMVY8hrrvza2j31JGaKYqCNYSC8Jf5EV7ONQhYGgQeRVxn8j<br>S8UhLOFXDdNtgHwKi02tF1bmb3Ko/s3vzPvFB8C7CsYRtHAzcx/xor2/CbT0QGYf<br>UQIDAQAB<br>-----END PUBLIC KEY-----`<br>    const jwKeys = await Promise.all([<br>        JWK.asKey(privateKey, &quot;pem&quot;),<br>        JWK.asKey(publicKey, &quot;pem&quot;)<br>    ]);<br>    let keystore = JWK.createKeyStore();<br>    await keystore.add(jwKeys[0]);<br>    await keystore.add(jwKeys[1]);<br>}<br>makeKeys();</pre><p>The method JWK.asKey is used to import keys from PEM formatted strings. The key format can be passed as the second parameter to the method and it returns JWK formatted key as the output. The imported key can be added to the key store and later passed when encrypting and decrypting the JWE token.</p><p><strong>JWE generation sample code:</strong></p><pre>const { JWK, JWE } = require(&#39;node-jose&#39;);<br>encrypt = async (raw, format = &#39;compact&#39;, contentAlg = &quot;A256GCM&quot;, alg = &quot;RSA-OAEP&quot;) =&gt; {<br>    let _publicKey = `-----BEGIN PUBLIC KEY-----<br>MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAwiSxcx5xFsNCjfDTOXz0<br>M6RivgPXTTKb/PH6/x4vYl1xg/vIrG1yDGyFuyAizxNaGtA+qo2CvM3iATyDWQg3<br>/8vDWiD4cIvUD2WE3XXewjyeGzQso26DceRxopI2tlSgvznjifetGCp+oj4BWrTC<br>qLF1AsR2ioUS7vuXMlpxXFhJfyEGoWuQaZDwoz7CZv1KrQwlRTtkqtn4IeXpVcgW<br>hg/1r0iRsvNJDokyiMVY8hrrvza2j31JGaKYqCNYSC8Jf5EV7ONQhYGgQeRVxn8j<br>S8UhLOFXDdNtgHwKi02tF1bmb3Ko/s3vzPvFB8C7CsYRtHAzcx/xor2/CbT0QGYf<br>UQIDAQAB<br>-----END PUBLIC KEY-----`<br>    let publicKey = await JWK.asKey(_publicKey, &quot;pem&quot;);<br>    const buffer = Buffer.from(JSON.stringify(raw))<br>    const encrypted = await JWE.createEncrypt({ format: format, contentAlg: contentAlg, fields: { alg: alg } }, publicKey)<br>        .update(buffer).final();<br>    return encrypted;<br>}<br>let raw = {<br>    &quot;mobileNumber&quot;: &quot;1234567890&quot;,<br>    &quot;customerId&quot;: &quot;000000000&quot;,<br>    &quot;sessionId&quot;: &quot;3a600342-a7a3-4c66-bbd3-f67de5d7096f&quot;,<br>    &quot;exp&quot;: 1645544094,<br>    &quot;jti&quot;: &quot;f3902a08-0e24-4dcc-bed1-f4cd9611bfad&quot;<br>};<br>encrypt(raw);</pre><p>JWE is encrypted with loaded publicKey, The line below can be used to explain the encryption process. It is important to understand the encryption process to figure out the usage of these parameters</p><pre>const encrypted = await JWE.createEncrypt({ format: format, contentAlg: contentAlg, fields: { alg: alg } }, publicKey).update(buffer).final()</pre><p><strong><em>format</em></strong>: Serialization formats, JWE has two serialization formats called <em>compact serialization </em>and <em>JSON serialization </em>which represent the encrypted payload.</p><p><strong><em>contentAlg</em></strong>: Content encryption algorithm (A256GCM)</p><p><strong><em>alg</em></strong>: CEK key encryption algorithm (RSA-OAEP)</p><h4>The Encryption Process:</h4><p>The <strong><em>contentAlg </em></strong>(A256GCM) is the content-encryption algorithm which is <strong>AES </strong>(Advanced Encryption Standard<strong><em> </em></strong>) <strong>GCM </strong>(Galois Counter Mode) algorithm with a 256-bit key. It is a symmetric key that is faster in large content encryption. The <strong>CEK</strong>(content-encryption key) is a random 256-bit key generated by the library which encrypts the payload. The encrypted key is also encrypted using the algorithm defined by the <strong>algo </strong>property.</p><p>The <strong><em>algo </em></strong>(RSA-OAEP) which asymmetric encryption uses the RSA algorithm with <strong>OAEP </strong>(Optimal Asymmetric Encryption Padding) method. The encrypted CEK is also placed in the JWE token which can be used by the receiver to decrypt the payload. This method is called key encryption or key wrapping. More detail can be found in the <a href="https://tools.ietf.org/html/draft-ietf-jose-json-web-algorithms-40#section-4.1">RFC</a></p><p><strong>The JWE token produced by the above code:</strong></p><blockquote>‘eyJhbGciOiJSU0EtT0FFUCIsImVuYyI6IkEyNTZHQ00iLCJraWQiOiJHUHZ0TFN3S29BMTJ1aW9Xc3IzeWhhdWNJWG12RHVUbWNUcXk1QS1EbVZzIn0.ai5j5Kk43skqPLwR0Cu1ZIyWOTUpLFKCN5cuZzxHdp0eXQjYLGpj8jYvU8yTu9rwZQeN9EY0_81hQHXEzMQgfCsRm0HXjcEwXIny-FH8N2WtYCjWrQubAIbnrqnNP-8TeCNZaShEMwYcVLUls8Yik2s6LiHTb9FTNfbMxyBlaQ4v8Q2rnKQ4tto5IG7D_dRC59WDmN2XkVfw3DWNbOxb34wgKHq0Zb7YcflQyXYxqkOAU9Xeuv_urFAhUyCzHt8W2vbqUtSosmHGoLf64QKUwqKietOVEI8tAruj-JTHUTR4P_-ZHy9jEgTNQLfZlkBDEDnXme2tcYqHj9XiidiXpw.thh69dp0Pz73kycQ.eF5bjuqtF60gW8O8cXKiYyDsBPX8OL0GQfhOxwGWUmYtHOds7FJWTNoSFnv5E6A_Bgn_2W2JUD1kniYUR1yOPnEJfHQ_SXMLJECZ8mBpHlYZWl3–39nGESxfdx1oXP1pO_ahP9eWtBCeS3X8DgPV0sLu1N-0ox6iZxTQ_PU314yTiUobhemNfT9ORghnOSApHi_HCKk9G1ABklbP82flcBfzA1tWKBw.HRhA5nn8HLsvYf8F-BzQew’</blockquote><p>The <em>compact serialized</em> token generated consists of five base64 URL encoded sections separated by period (.).</p><p><strong>those are…</strong></p><ol><li>JOSE header: {“alg”:”RSA-OAEP”,”enc”:”A256GCM”,”kid”:”GPvtLSwKoA12uioWsr3yhaucIXmvDuTmcTqy5A-DmVs”}</li><li>Encrypted CEK</li><li>Encrypted payload (by CEK)</li><li>Initialized vector</li><li>Authentication Tag</li></ol><p><strong>Equivalent JSON serialization looks like below.</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*CgZLnu0YM1QUtiOv4K6GUg.png" /><figcaption>JSON serialized token</figcaption></figure><p><strong>Decryption and Verification:</strong></p><p>The sample code decrypts and returns the plain text claims from the <em>compact serialized</em> JWE token generated in previous steps. Observe how the private key is used to decrypt the token which was encrypted using the public key.</p><pre>const { JWK, JWE, parse } = require(&#39;node-jose&#39;);<br>decrypt = async (encryptedBody) =&gt; {<br>    let _privateKey = `-----BEGIN RSA PRIVATE KEY-----<br>MIIEowIBAAKCAQEAwiSxcx5xFsNCjfDTOXz0M6RivgPXTTKb/PH6/x4vYl1xg/vI<br>rG1yDGyFuyAizxNaGtA+qo2CvM3iATyDWQg3/8vDWiD4cIvUD2WE3XXewjyeGzQs<br>o26DceRxopI2tlSgvznjifetGCp+oj4BWrTCqLF1AsR2ioUS7vuXMlpxXFhJfyEG<br>oWuQaZDwoz7CZv1KrQwlRTtkqtn4IeXpVcgWhg/1r0iRsvNJDokyiMVY8hrrvza2<br>j31JGaKYqCNYSC8Jf5EV7ONQhYGgQeRVxn8jS8UhLOFXDdNtgHwKi02tF1bmb3Ko<br>/s3vzPvFB8C7CsYRtHAzcx/xor2/CbT0QGYfUQIDAQABAoIBADgdoQj0UJ3SvKcI<br>aBViz7cpmbzwoUfYDAx16SXalLmq5sfOfDeSvvdmWtU2ubj/D/lWHfbwRkzKebv/<br>wLt4S69tNz8S7pyhXh9BKcFVc5jTKqQUVZ67r9S4wjvKZXQYTApZ8jIL3AVzKv08<br>TOnp+6YE/RxaqyToyAs5v383czLMdSM9bThDw+IZHfKFcl2iyUI4XVaPLDZPzUlG<br>MW13ypwFQXbdro9pnMs9v2573WumIVvbiLqIdxK1anag0KbCnCY2hDmoLNv7Mohz<br>1pFiqEStI6DQsYfEm/geIIL9nLhA8QJ28B9DtLKqRN7oWl2w5BiMEDCrmVK/4niM<br>lsqF1ZECgYEA5zVsjoJzRCBgZ5dRx9BOu9MKXQ+h00LS3+JaApEzW+QV0DplTvb5<br>aRUHhTIhUig2WdQVrEiBVXKg9eYmOBXOpX5pgDO5XJ16KcjdHcwMwoYAcUPIT5Y2<br>tMgoX+jCgTt95cnLKhAnSlH9cCyq+nmcdfDNuvNx8HJO7P33MaVDHCUCgYEA1vXX<br>cBWM+sGkUxpJNwlgA8bO7xq2kpbM3gqa0z6SKQhxnnmPyoKsZSHdwQMUCKIWBLjU<br>n27STmXm2SblT1cT39MCED2t0U7N2D1KUQfZkFaN4gImF77iZBWIfDLObAom6JKg<br>gER0glakAjbDMKq90mVzrKrR6XsD3az+AJE1eL0CgYBbHKB04E9QD3ouGGFv3lTI<br>i3fQCHL676Bt/aL+0/1rPsyhzAFURtsuX80g3gpnd9VDPOJ1i/T7mTp47IMvItjW<br>OqSUks1/A8e6Y59POLPmjCvsdoufYVCZmS7f7LeJeco5HXZkUw1Iqlq3M8MFBZt0<br>lrpb68eAu2sC1WnuNHPnyQKBgQC1LFb7vO4pmnOpJwp2PIyUIkfe9qDSRA8/Rajg<br>Smhd9SPt8X7jq+cpBbYlKzcDX7k3GaD7DyhpszEx7LpweG/jwbCHh7SsKMMNcfrk<br>+LzCDnFe/3ijotqkiBGUvC2GmbfZZVupQAkCoYtx4j35Eq8SWTd5XC+3nVrQxzD9<br>wWVT8QKBgBylVSsVeU7H/RT3RZ/qgWnpllBzGJic8X6lfyTHVD/9dO9XMzuD7R+/<br>VFc9Ib71QPzyq39BX+YiCI+xwDGARgO3GGA4vxvF46Tq0rYUpZ1LiC4raO4I5xrl<br>NxZCLVlhLWU27FR7xu8YN18mRCCwz1FCcsEtNU4nrBK2IIIwGLCf<br>-----END RSA PRIVATE KEY-----`;</pre><pre>    let keystore = JWK.createKeyStore();<br>    await keystore.add(await JWK.asKey(_privateKey, &quot;pem&quot;));<br>    let outPut = parse.compact(encryptedBody);<br>    let decryptedVal = await outPut.perform(keystore);<br>    let claims = Buffer.from(decryptedVal.plaintext).toString();<br>    return claims;<br>}</pre><pre>decrypt(&#39;eyJhbGciOiJSU0EtT0FFUCIsImVuYyI6IkEyNTZHQ00iLCJraWQiOiJHUHZ0TFN3S29BMTJ1aW9Xc3IzeWhhdWNJWG12RHVUbWNUcXk1QS1EbVZzIn0.ai5j5Kk43skqPLwR0Cu1ZIyWOTUpLFKCN5cuZzxHdp0eXQjYLGpj8jYvU8yTu9rwZQeN9EY0_81hQHXEzMQgfCsRm0HXjcEwXIny-FH8N2WtYCjWrQubAIbnrqnNP-8TeCNZaShEMwYcVLUls8Yik2s6LiHTb9FTNfbMxyBlaQ4v8Q2rnKQ4tto5IG7D_dRC59WDmN2XkVfw3DWNbOxb34wgKHq0Zb7YcflQyXYxqkOAU9Xeuv_urFAhUyCzHt8W2vbqUtSosmHGoLf64QKUwqKietOVEI8tAruj-JTHUTR4P_-ZHy9jEgTNQLfZlkBDEDnXme2tcYqHj9XiidiXpw.thh69dp0Pz73kycQ.eF5bjuqtF60gW8O8cXKiYyDsBPX8OL0GQfhOxwGWUmYtHOds7FJWTNoSFnv5E6A_Bgn_2W2JUD1kniYUR1yOPnEJfHQ_SXMLJECZ8mBpHlYZWl3-39nGESxfdx1oXP1pO_ahP9eWtBCeS3X8DgPV0sLu1N-0ox6iZxTQ_PU314yTiUobhemNfT9ORghnOSApHi_HCKk9G1ABklbP82flcBfzA1tWKBw.HRhA5nn8HLsvYf8F-BzQew&#39;);</pre><h4>Conclusion</h4><p>This article explains JWT basics and mainly how JWE works. The code samples added have hardcoded keys and certificates, which are mainly to explain how things work. It is not a recommended practice to hardcode sensitive information in the code, Please take the necessary measurements such as KMS or vault to store and access keys/certificates.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7595542565d0" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Builder and Composite design patterns C#]]></title>
            <link>https://sukithaj.medium.com/builder-and-composite-design-patterns-c-1cd1425a5f89?source=rss-49dd67ef6d69------2</link>
            <guid isPermaLink="false">https://medium.com/p/1cd1425a5f89</guid>
            <category><![CDATA[design-patterns]]></category>
            <category><![CDATA[clean-code]]></category>
            <category><![CDATA[oop]]></category>
            <category><![CDATA[c-sharp-programming]]></category>
            <dc:creator><![CDATA[Sukitha Jayasinghe]]></dc:creator>
            <pubDate>Wed, 10 Mar 2021 09:30:10 GMT</pubDate>
            <atom:updated>2021-03-22T04:28:44.732Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2C2Sl-GlJV7ki9eTv59Sgw.jpeg" /></figure><p>The composite design pattern is a common structural design pattern that composes objects in a tree structure and provides an interface to work with them as they were individual objects. This pattern creates a tree structure with objects inherited from the same base and provides a nice abstraction over the structure.</p><p><strong>Apply this design pattern when:</strong></p><ul><li>Require generic function on top of hierarchical structure</li><li>Require to treat complex and individual objects uniformly</li></ul><p><strong>Purpose:</strong></p><ul><li>Adding new elements to the structure without breaking the code preserves the Open-Closed Principle</li></ul><p><strong>Real word examples:</strong></p><p>Popular use case of this pattern is Directory/Folder structure, HTML tags. JSON structure, YAML structure and XML. The .net XElement class is implemented using the composite pattern.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*YgbNhLplEPRiP3EAJxzf9w.png" /><figcaption>XContainer document from official Microsoft site</figcaption></figure><p>XContainer abstract class can be considered as the base, both XDocument and XElements inherited from it. XDocument and XElement both can be considered as composites. You can read more from the <a href="https://docs.microsoft.com/en-us/dotnet/api/system.xml.linq.xnode?view=net-5.0">official site</a></p><p><strong>Example:</strong></p><p>In this example, a lighter version of XElement is implemented for demonstration purposes.</p><p><strong>Class diagram:</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/649/1*MUCe-u8QeUjTTbpI5qYyyA.png" /><figcaption>Composite design</figcaption></figure><p><strong><em>IXElement.cs</em></strong></p><p>This is the composite interface that describes common methods such as Add() and Remove() for XML document and XML Elements.</p><pre>using System;<br>using System.Collections.Generic;<br>using System.Text;</pre><pre>namespace Composite<br>{<br>    public interface IXElement<br>    {<br>        string XName { get; }<br>        void Add(IXElement element);<br>        void Remove(IXElement element);<br>        List&lt;IXElement&gt; Elements();</pre><pre>    }<br>}</pre><p><strong><em>XDocument.cs</em></strong></p><p>Implementation of the XML document, This has an additional property to keep a comment on. This class has two constructors, one is with comment and the other one with comment and list of parameters, which supports passing a list of XML elements on creation.</p><pre>using System;<br>using System.Collections.Generic;<br>using System.Text;</pre><pre>namespace Composite<br>{<br>    public class XDocument : IXElement<br>    {<br>        private readonly List&lt;IXElement&gt; children;</pre><pre>        public string XName { get; }<br>        public string Comment { get;  }<br>        public XDocument(string _comment, params IXElement[] items)<br>        {   </pre><pre>            children = new List&lt;IXElement&gt;();<br>            Comment = _comment;<br>            foreach (var _item in items) {<br>                children.Add(_item);<br>            }<br>        }<br>        public XDocument(string _comment)<br>        {<br>            children = new List&lt;IXElement&gt;();<br>            Comment = _comment;<br>        }<br>        public void Add(IXElement element)<br>        {<br>            children.Add(element);<br>        }<br>        public void Remove(IXElement element)<br>        {<br>            children.Remove(element);<br>        }<br>        public override string ToString()<br>        {<br>            var document = new StringBuilder().Append($&quot;&lt; !--{Comment}--&gt;&quot;);<br>            document.Append(&quot;&lt;Root&gt;&quot;);<br>            foreach (var item in children) {<br>                document.Append(item.ToString());<br>            }<br>            document.Append(@&quot;&lt;\Root&gt;&quot;);<br>            return document.ToString();<br>        }<br>        public List&lt;IXElement&gt; Elements()<br>        {<br>            return children;<br>        }<br>    }<br>}</pre><p><strong><em>XElement.cs</em></strong></p><p>This is the implementation of the XML element. This class has three constructors with a combination of name, value, and element parameter list. This provides the caller with the flexibility of creating XML elements with and without inner elements.</p><pre>using System;<br>using System.Collections.Generic;<br>using System.Text;</pre><pre>namespace Composite<br>{<br>    public class XElement : IXElement<br>    {<br>        public string XValue { get; }</pre><pre>        private readonly List&lt;IXElement&gt; children;</pre><pre>        public string XName { get; }</pre><pre>        public XElement(string name)<br>        {<br>            XName = name;<br>            children = new List&lt;IXElement&gt;();</pre><pre>        }<br>        public XElement(string name, string value)<br>        {<br>            XName = name;<br>            XValue = value;<br>            children = new List&lt;IXElement&gt;();</pre><pre>        }<br>        public XElement(string name, params IXElement[] items)<br>        {<br>            children = new List&lt;IXElement&gt;();<br>            XName = name;<br>            foreach (var _item in items)<br>            {<br>                children.Add(_item);<br>            }<br>        }<br>        public void Add(IXElement element)<br>        {<br>            children.Add(element);<br>        }<br>        public void Remove(IXElement element)<br>        {<br>            children.Remove(element);<br>        }<br>        public override string ToString()<br>        {<br>            var document = new StringBuilder();<br>            document.Append($&quot;&lt;{XName}&gt;&quot;);<br>            if (children.Count &gt; 0)<br>            {<br>                foreach (var item in children)<br>                {<br>                    document.Append(item.ToString());<br>                }<br>            }<br>            else {<br>                if(XValue != null)<br>                document.Append(XValue.ToString());<br>            }<br>            document.Append(@&quot;&lt;\&quot;+XName+&quot;&gt;&quot;);<br>            return document.ToString();<br>        }<br>        public List&lt;IXElement&gt; Elements()<br>        {<br>            return children;<br>        }<br>    }<br>}</pre><p><strong><em>main.cs</em></strong></p><p>In the main method, XML Document is created by passing the comment and list of XML elements to the constructor. Observe the ability to pass the hierarchy of elements in the constructor.</p><pre>using Composite;<br>using System;</pre><pre>namespace Main<br>{<br>    class Program<br>    {<br>        static void Main(string[] args)<br>        {<br>            XDocument document = new XDocument(&quot;This is the root element&quot;, <br>                new XElement(&quot;child1&quot;, <br>                    new XElement(&quot;child1.1&quot;, <br>                        new XElement(&quot;child1.1.1&quot;, &quot;1.1.1&quot;))),<br>                new XElement(&quot;child2&quot;, &quot;2&quot;),<br>                new XElement(&quot;child3&quot;, &quot;3&quot;),<br>                new XElement(&quot;child4&quot;, &quot;4&quot;));<br>            var element5 = new XElement(&quot;child4&quot;, &quot;5&quot;);<br>            document.Add(element5);<br>            Console.WriteLine(document);<br>            document.Remove(element5);<br>            Console.WriteLine(document);<br>        }<br>    }<br>}</pre><p><strong>Relationship with other patterns:</strong></p><p>In the real world, patterns don’t exist individually but are woven together to provide solutions to complex design problems.</p><ul><li><strong><em>Builder</em></strong>: Can use when creating complex tree structures</li><li><strong><em>Iterator</em></strong>: Iterates through the complex structure</li><li><strong><em>Flyweight</em></strong>: Save memory resources when creating objects</li></ul><p>The above example extends with a builder to demonstrate how the pattern works together. The XML construction above seems a bit messy so a fluent builder is added to simplify the XML creation process.</p><p>Previous article about the <a href="https://sukithaj.medium.com/builder-design-pattern-fluent-interface-c-70cae9490a91">Builder pattern</a>.</p><p><strong>Class Diagram with Builder</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*BYtRxxnaQq3XrklAzQK85w.png" /><figcaption>class diagram with the builder</figcaption></figure><p><strong><em>IXMLBuilder.cs</em></strong></p><p>This interface provides methods to add elements and reset the structure.</p><pre>namespace Builder<br>{<br>    public interface IXMLBuilder<br>    {<br>        public XDocument Root { get; }<br>        IXMLBuilder AddElement(string name, string value);<br>        IXMLBuilder AddElement(string name);<br>        IXMLBuilder MoveTo(string name);<br>        IXMLBuilder Reset();</pre><pre>    }<br>}</pre><p><strong><em>XMLBuilder.cs</em></strong></p><p>Implementation of builder interface which has the root document and simple logic to add elements.</p><pre>using Composite;<br>using System;<br>using System.Collections.Generic;<br>using System.Linq;<br>using System.Text;</pre><pre>namespace Builder<br>{<br>    public class XMLBuilder : IXMLBuilder<br>    {<br>        public XDocument Root { get; }<br>        internal IXElement Current { get; set; }<br>        public XMLBuilder(string comment) {<br>            Root = new XDocument(comment);<br>            Current = Root;<br>        }<br>        public IXMLBuilder AddElement( string name, string value)<br>        {<br>            Current.Add(new XElement(name, value));<br>            return this;<br>        }<br>        public IXMLBuilder MoveTo(string name)<br>        {<br>            List&lt;IXElement&gt; filtered = Current.Elements().Where(x =&gt; x.XName == name).ToList();<br>            Current = filtered.Count &gt; 0 ? filtered[0] : Root;<br>            return this;<br>        }<br>        public IXMLBuilder Reset()<br>        {<br>            Current = Root;<br>            return this;<br>        }<br>        public IXMLBuilder AddElement(string name)<br>        {<br>            var temp = new XElement(name);<br>            Current.Add(temp);<br>            Current = temp;<br>            return this;<br>        }<br>    }<br>}</pre><p><strong><em>main.cs</em></strong></p><p>A simpler way of building the XML tree using the builder interface.</p><pre>using Builder;<br>using Composite;<br>using System;</pre><pre>namespace Main<br>{<br>    class Program<br>    {<br>        static void Main(string[] args)<br>        {</pre><pre>                XDocument xdocument = new XMLBuilder(&quot;This is the root element&quot;)<br>                .AddElement(&quot;child1&quot;)<br>                .AddElement(&quot;child1.1&quot;)<br>                .AddElement(&quot;child1.1.1&quot;, &quot;1.1.1&quot;)<br>                .Reset()<br>                .AddElement(&quot;child2&quot;, &quot;2&quot;)<br>                .AddElement(&quot;child2&quot;, &quot;3&quot;)<br>                .AddElement(&quot;child2&quot;, &quot;4&quot;)<br>                .AddElement(&quot;child2&quot;, &quot;5&quot;)<br>                .Root;</pre><pre>                 Console.WriteLine(xdocument);<br>        }<br>    }<br>}</pre><p>Discussion:</p><p>Some argue that the original pattern is violating the <a href="https://en.wikipedia.org/wiki/Liskov_substitution_principle"><strong><em>Liskov substitutional principle</em></strong></a> and <a href="https://en.wikipedia.org/wiki/Interface_segregation_principle"><strong><em>Interface segregation principle</em></strong></a> by forcing leaf nodes to implement meaningless methods such as Add() or Remove(). However, The sample provided in this article complies with ISP and LSP, as XElement and XDocument has implemented all abstract methods.</p><p>Thank you, <a href="https://medium.com/u/36cefa51daac">Desmond Harris Fernando</a> and <a href="https://medium.com/u/702c7758a2a3">Dinusha Kannangara</a> for reviewing the code.</p><p>Source code available in <a href="https://github.com/sukitha/CompositePattern.git">git</a>,</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1cd1425a5f89" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Builder design pattern (Fluent Interface C++)]]></title>
            <link>https://sukithaj.medium.com/builder-design-pattern-fluent-interface-c-70cae9490a91?source=rss-49dd67ef6d69------2</link>
            <guid isPermaLink="false">https://medium.com/p/70cae9490a91</guid>
            <category><![CDATA[design-patterns]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[clean-code]]></category>
            <category><![CDATA[csharp]]></category>
            <dc:creator><![CDATA[Sukitha Jayasinghe]]></dc:creator>
            <pubDate>Sun, 28 Feb 2021 11:40:36 GMT</pubDate>
            <atom:updated>2021-03-23T02:00:06.104Z</atom:updated>
            <content:encoded><![CDATA[<h3>Builder design pattern (Fluent Interface in C++ and C#)</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ioDLgO4DKCvZihc22Ydplw.jpeg" /></figure><p>The builder design pattern is a simple but powerful creational pattern which decouples object construction from implementation by encapsulating complex object construction logic and delegate the construction responsibility to separate classes. The pattern is suitable for building multiple representations from the same object.</p><blockquote>Builder pattern builds a complex object using simple objects and using a step by step approach. This type of design pattern comes under creational pattern as this pattern provides one of the best ways to create an object. [<a href="https://www.tutorialspoint.com/design_pattern/builder_pattern.htm">by tutorialspoint</a>]</blockquote><p>Apply builder design pattern based on <a href="https://en.wikipedia.org/wiki/Code_smell#:~:text=In%20computer%20programming%2C%20a%20code,%2C%20developer%2C%20and%20development%20methodology.&amp;text=It%20is%20also%20a%20term%20used%20by%20agile%20programmers.">Code Smells</a>:</p><ul><li>Your class has a constructor with several optional arguments</li><li>Complex logic and multiple condition checks in the constructor</li><li>Some parameter combinations are disallowed (ex: continent and country)</li></ul><p>Example:</p><p>This example demonstrates how to utilize builder patterns to construct email objects using multiple builder classes with a fluent interface. Here email object is constructed in multiple stages with header and body builder classes. Each builder has series of methods such as <strong><em>from()</em></strong> , <strong><em>to()</em></strong> and <strong><em>subject()</em></strong>. This example might look a little overengineered as the used email is not very complex.</p><p><strong><em>email.h</em></strong></p><p><em>This is the email class that has private variables like </em><em>from, </em><em>to, </em><em>subject, </em><em>body and </em><em>attachment. Email class has a set of friend classes in-order for them to access the above private variables. The constructor is made private to prevent creating email objects directly from other classes.</em></p><pre>#pragma once<br>#include &lt;string&gt;<br>#include &lt;sstream&gt;<br>class EmailBuilder;</pre><pre>class Email<br>{<br>public:<br>    friend class EmailBuilder;<br>    friend class EmailHeaderBuilder;<br>    friend class EmailBodyBuilder;<br>    friend std::ostream &amp;operator&lt;&lt;(std::ostream &amp;os, const Email &amp;obj);<br>    static EmailBuilder create();</pre><pre>private:<br>    Email() = default;</pre><pre>    std::string m_from;<br>    std::string m_to;<br>    std::string m_subject;<br>    std::string m_body;<br>    std::string m_attachment;<br>};</pre><p><strong><em>email.cpp</em></strong></p><p>operator (&lt;&lt;) overloaded to output variables in a user-friendly format.</p><pre>#include &quot;email.h&quot;<br>#include &quot;emailbuilder.h&quot;<br>EmailBuilder Email::create()<br>{<br>    return EmailBuilder{};<br>}<br>std::ostream &amp;operator&lt;&lt;(std::ostream &amp;os, const Email &amp;obj)<br>{<br>    return os<br>           &lt;&lt; &quot;from: &quot; &lt;&lt; obj.m_from &lt;&lt; std::endl<br>           &lt;&lt; &quot;to: &quot; &lt;&lt; obj.m_to &lt;&lt; std::endl<br>           &lt;&lt; &quot;subject: &quot; &lt;&lt; obj.m_subject &lt;&lt; std::endl<br>           &lt;&lt; &quot;body: &quot; &lt;&lt; obj.m_body &lt;&lt; std::endl<br>           &lt;&lt; &quot;attachment: &quot; &lt;&lt; obj.m_attachment &lt;&lt; std::endl;<br>}</pre><p><strong><em>abstractEmailBuilder.h</em></strong></p><p>Base builder class has builder create methods such as header() and body() to get required builder implementation. It has a forward class declaration for EmailBodyBuilder and EmailHeaderBuilder. Cast operator for Email is also overloaded to return the final constructed email object ownership to the caller.</p><pre>#pragma once<br>#include &quot;email.h&quot;<br>class EmailHeaderBuilder;<br>class EmailBodyBuilder;<br>class AbstractEmailBuilder<br>{<br>protected:<br>    Email &amp;m_email;<br>    explicit AbstractEmailBuilder(Email &amp;email) : m_email(email) {}<br>public:<br>    operator Email() const<br>    {<br>        return std::move(m_email);<br>    };<br>    EmailHeaderBuilder header() const;<br>    EmailBodyBuilder body() const;<br>};</pre><p><strong><em>abstractEmailBuilder.cpp</em></strong></p><pre>#include &quot;abstractEmailBuilder.h&quot;<br>#include &quot;emailbuilder.h&quot;<br>#include &quot;emailBodyBuilder.h&quot;<br>#include &quot;emailHeaderBuilder.h&quot;<br>EmailHeaderBuilder AbstractEmailBuilder::header() const<br>{<br>    return EmailHeaderBuilder{m_email};<br>};<br>EmailBodyBuilder AbstractEmailBuilder::body() const<br>{<br>    return EmailBodyBuilder{m_email};<br>};</pre><p><strong><em>emailBuilder.h</em></strong></p><p>A concrete class implementation that initializes email object and passes it to the abstract class. This will allow Builder classes to access the object.</p><pre>#pragma once<br>#include &quot;email.h&quot;<br>#include &quot;abstractEmailBuilder.h&quot;<br>class EmailBuilder : public AbstractEmailBuilder<br>{<br>    Email m_email;<br>public:<br>    EmailBuilder() : AbstractEmailBuilder{m_email}<br>    {<br>    }<br>};</pre><p><strong><em>emailBodyBuilder.h</em></strong></p><p>Demonstrate email body creation using EmailBodyBuilder concrete class.</p><pre>#pragma once<br>#include &lt;string&gt;<br>#include &quot;emailbuilder.h&quot;<br>class EmailBodyBuilder : public AbstractEmailBuilder<br>{<br>public:<br>    explicit EmailBodyBuilder(Email &amp;email)<br>        : AbstractEmailBuilder{email}<br>    {<br>    }<br>    EmailBodyBuilder &amp;body(const std::string &amp;body)<br>    {<br>        m_email.m_body = body;<br>        return *this;<br>    }<br>    EmailBodyBuilder &amp;attachment(const std::string &amp;attachment)<br>    {<br>        m_email.m_attachment = attachment;<br>        return *this;<br>    }<br>};</pre><p><strong><em>emailHeaderBuilder.h</em></strong></p><p>Demonstrate email header creation using EmailHeaderBuilder concrete class.</p><pre>#pragma once<br>#include &lt;string&gt;<br>#include &quot;emailbuilder.h&quot;<br>class EmailHeaderBuilder : public AbstractEmailBuilder<br>{<br>public:<br>    explicit EmailHeaderBuilder(Email &amp;email)<br>        : AbstractEmailBuilder{email}<br>    {<br>    }<br>    EmailHeaderBuilder &amp;from(const std::string &amp;from)<br>    {<br>        m_email.m_from = from;<br>        return *this;<br>    }<br>    EmailHeaderBuilder &amp;to(const std::string &amp;to)<br>    {<br>        m_email.m_to = to;<br>        return *this;<br>    }<br>    EmailHeaderBuilder &amp;subject(const std::string &amp;subject)<br>    {<br>        m_email.m_subject = subject;<br>        return *this;<br>    }<br>};</pre><p><strong><em>main.cpp</em></strong></p><pre>#include &lt;iostream&gt;<br>#include &lt;sstream&gt;<br>#include &lt;string&gt;<br>#include &quot;email.h&quot;<br>#include &quot;emailbuilder.h&quot;<br>#include &quot;emailHeaderBuilder.h&quot;<br>#include &quot;emailBodyBuilder.h&quot;<br>using namespace std;<br>int main()<br>{<br>    Email mail = Email::create()<br>                     .header()<br>                         .from(&quot;test1<a href="/service/mailto:sukithaj@gmail.com">@example.com</a>&quot;)<br>                         .to(&quot;<a href="/service/mailto:test@gmail.com">test2@</a><a href="/service/mailto:sukithaj@gmail.com">example</a><a href="/service/mailto:test@gmail.com">.com</a>&quot;)<br>                         .subject(&quot;This is a test mail&quot;)<br>                     .body()<br>                         .body(&quot;This is a test body&quot;)<br>                         .attachment(&quot;This is a test attachment&quot;);<br>    std::cout &lt;&lt; mail &lt;&lt; std::endl;<br>}</pre><p><strong>Conclusion</strong></p><p>There are few variations of builder design pattern, this example is Fluent Interface like Implementation for c++. The common implementation is using directory-based class structure. There are lots of resources available online if you want to learn more.</p><p>The ideal time to apply design patterns is the refactoring phase. Code smells are the best way to find what are the changes required and which classes and codes segments require changes. I will write more stories related to code smells in the future.</p><p>Thank you <a href="https://medium.com/u/36cefa51daac">Desmond Harris Fernando</a> for reviewing the <a href="https://github.com/sukitha/BuilderPattern">C# code</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=70cae9490a91" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>