<?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 Isuru Aravinda on Medium]]></title>
        <description><![CDATA[Stories by Isuru Aravinda on Medium]]></description>
        <link>https://medium.com/@iaravinda33?source=rss-6397f9c14ff1------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*o44kU68JUF_zU5JLF5MpYw.jpeg</url>
            <title>Stories by Isuru Aravinda on Medium</title>
            <link>https://medium.com/@iaravinda33?source=rss-6397f9c14ff1------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Fri, 20 Nov 2026 00:14:49 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@iaravinda33/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[Understanding the 12-Factor App Through Simple Real-World Examples]]></title>
            <link>https://medium.com/@iaravinda33/understanding-the-12-factor-app-through-simple-real-world-examples-7ed30dd63a4e?source=rss-6397f9c14ff1------2</link>
            <guid isPermaLink="false">https://medium.com/p/7ed30dd63a4e</guid>
            <category><![CDATA[cloud-computing]]></category>
            <category><![CDATA[design-systems]]></category>
            <category><![CDATA[cloud-native]]></category>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[backend-development]]></category>
            <dc:creator><![CDATA[Isuru Aravinda]]></dc:creator>
            <pubDate>Wed, 15 Jul 2026 19:28:41 GMT</pubDate>
            <atom:updated>2026-07-15T19:28:41.454Z</atom:updated>
            <content:encoded><![CDATA[<p><em>A beginner-friendly guide to building scalable, maintainable, and cloud-ready applications without getting lost in technical jargon.</em></p><h3>It Always Starts Small</h3><p>Every developer has been here.</p><p>You create a folder called <strong>final-project</strong>.</p><p>Inside it is one application, one database running on your laptop, and a .env file that somehow ends up on GitHub because &quot;I&#39;ll remove it later.&quot;</p><p>Everything works perfectly.</p><p>Then your classmates start using it.</p><p>Your lecturer wants a demo.</p><p>Someone suggests deploying it to the cloud.</p><p>Suddenly…</p><ul><li>The database only exists on your laptop.</li><li>API keys are accidentally committed to Git.</li><li>Deployments become stressful.</li><li>“It works on my machine” becomes everyone’s favorite excuse.</li></ul><p>Your little side project has officially grown up.</p><p>This is exactly the problem the <strong>12-Factor App</strong> methodology was created to solve.</p><p>Instead of telling you <strong>what technologies to use</strong>, it teaches <strong>how to build applications that continue working as they grow.</strong></p><p>Let’s explore each principle with simple examples.</p><h3>1. Codebase — One Source of Truth</h3><p>Imagine three developers each have their own copy of the application. One fixes a bug, another adds a feature, and the third accidentally deletes both. Nobody knows which version is the “real” application.</p><p>The first factor says an application should have <strong>one codebase</strong> tracked with version control, while multiple deployments (development, testing, production) come from that same source.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/316/1*qkfDr-cP99znebvCx2FLFQ.png" /></figure><h3>Example</h3><p>Think of Google Docs.</p><p>Everyone edits the same document instead of emailing around “Report_v2_Final_Final_ReallyFinal.docx”.</p><p>A Git repository works the same way, there is one source of truth, while different branches allow people to work independently.</p><h3>2. Dependencies — Never Assume</h3><p>Applications shouldn’t secretly depend on software installed only on a developer’s laptop, and they shouldn’t quietly borrow anything sitting on the system either.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/298/1*IBLutZVThqBs_Y4Rm2NMwQ.png" /></figure><p>Applications shouldn’t secretly depend on software installed only on a developer’s laptop.</p><p>Every required library should be declared so anyone can recreate the environment.</p><h3>Example</h3><p>Imagine a cake recipe that says:</p><p>“Just use the special flour already in my kitchen.”</p><p>They can’t bake the cake because they don’t have that flour, so instead, you list every ingredient:</p><ul><li>Flour</li><li>Sugar</li><li>Eggs</li><li>Butter</li></ul><p>But listing ingredients isn’t enough on its own. If you bake in a kitchen that already has salt sitting on the counter from another recipe, you might use it without noticing, and the cake won’t reproduce the same way in a different kitchen. That’s why a real bakery works from a fully stocked, isolated kitchen containing <em>only</em> the declared ingredients nothing borrowed, nothing assumed.</p><p>Similarly, an application should both declare its dependencies explicitly (in requirements.txt, package.json, or a pom.xml) <em>and</em> isolate them using a virtual environment, container, or dependency manager so it never silently relies on a package that happens to be installed system-wide.</p><h3>3. Config — Keep Secrets Out of Code</h3><p>Configuration such as database credentials and API keys changes between environments, so it shouldn’t be hard-coded.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/277/1*9P1Gx2nbsKxlDOVUW7O0Ag.png" /></figure><h3>Example</h3><p>Your house key doesn’t come permanently glued to your front door.</p><p>You carry it separately and only use it when needed.</p><p>Environment variables work the same way.</p><p>The application knows <strong>where to look</strong> for the key but doesn’t permanently store it.</p><h3>4. Backing Services — Treat Everything Like a Plug</h3><p>Databases, caches, email providers, and storage services should be interchangeable.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/309/1*jA2eDLPpCVjC2jFDiWEG9w.png" /></figure><h3>Example</h3><p>Think about charging your phone.</p><p>You don’t redesign the phone when you buy a different charger.</p><p>You simply unplug one cable and plug in another.</p><p>Applications should treat databases the same way.</p><p>Switching from a local PostgreSQL database to Amazon RDS should mostly be changing a connection string.</p><h3>5. Build, Release, Run — Separate the Journey</h3><p>Software should move through three distinct stages, and critically, the same build must carry through unchanged; only the configuration around it changes.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/329/1*nmJcjLVUl42yQ063pw2pZg.png" /></figure><h3>Example</h3><p>Imagine a shipping container loaded at a factory.</p><ul><li><strong>Build</strong> → The container is packed and sealed.</li><li><strong>Release</strong> → The sealed container is labeled for a specific destination and combined with shipping instructions (config).</li><li><strong>Run</strong> → The container is delivered and opened.</li></ul><p>Nobody reopens the container and repacks it differently for each destination; that would defeat the purpose of sealing it in the first place. If a bug shows up in production, you don’t patch the running container; you go back, build a new sealed one, and release that.</p><p>A Docker image works the same way: you build it once, then run that exact same image in staging and production, changing only environment variables, never rebuilding the image per environment.</p><h3>6. Processes — Be Stateless</h3><p>Application processes shouldn’t store important information in memory.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/318/1*Nb4Lmd_An75w47JsBIIqyA.png" /></figure><h3>Example</h3><p>Suppose a waiter memorizes every customer’s order instead of writing it down.</p><p>If the waiter suddenly leaves, every order is lost.</p><p>A better approach is writing orders into the restaurant’s system.</p><p>Similarly, applications store important information in databases instead of memory.</p><h3>7. Port Binding — Bring Your Own Server</h3><p>Applications should expose themselves through a network port instead of depending on an external web server.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/299/1*2AUB_U32gXvEqC2oRNok5Q.png" /></figure><h3>Example</h3><p>Imagine opening a coffee shop.</p><p>Instead of asking another café to serve your coffee, you open your own shop with your own entrance.</p><p>When customers arrive, they know exactly where to find you.</p><p>A web application exposing port 8080 works similarly.</p><h3>8. Concurrency — Clone Yourself</h3><p>When traffic increases, create more application instances.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/275/1*_R6xAxT9jhOBhBiUas0IgQ.png" /></figure><h3>Example</h3><p>A supermarket doesn’t make one cashier work twice as fast.</p><p>It simply opens more checkout counters.</p><p>Applications scale exactly the same way.</p><h3>9. Disposability — Start Fast, Stop Gracefully</h3><p>Applications should start quickly and shut down safely.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/310/1*xWwUOiftY3Dr0S661nHf9A.png" /></figure><h3>Example</h3><p>Think of replacing a light bulb.</p><p>The old one is removed; the new one works immediately.</p><p>Customers shouldn’t even notice.</p><p>Modern cloud deployments aim for this same seamless replacement.</p><h3>10. Development and Production Should Feel Similar</h3><p>The fewer differences between development and production, the fewer surprises.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/329/1*colxsJtHN36aWsiQoLzDgw.png" /></figure><h3>Example</h3><p>Imagine practicing for a driving test in a small hatchback but taking the exam in a large truck.</p><p>Your skills may not transfer perfectly.</p><p>Developers should test software in an environment that closely resembles production.</p><h3>11. Logs — Let Them Flow</h3><p>Applications should treat logs as a simple stream of output written to stdout—and leave the job of storing, routing, or rotating them to the environment.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/443/1*-lN8fdYpuVrhZuO3kNT3fw.png" /></figure><h3>Example</h3><p>Think of a security camera.</p><p>It doesn’t decide where the footage is stored, how long to keep it, or which room gets to watch it live; it just records continuously and pushes the feed outward. A separate system handles archiving, monitoring, and access.</p><p>An application should behave the same way: write every log line straight to stdout as an unbuffered stream, and let the platform (Docker, Kubernetes, a log aggregator) decide where that stream goes. If your app is opening its own log files, rotating them, or deciding which server they get shipped to, it’s doing a job that isn’t its own.</p><h3>12. Admin Processes — Treat Maintenance Like Code</h3><p>Administrative tasks should use the same code and environment as the application.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/441/1*bYB-e7SyKj_3NFd_CcGcvg.png" /></figure><h3>Example</h3><p>Imagine a bank.</p><p>Employees don’t use a secret version of the banking software to create new accounts.</p><p>They use the same trusted system with special permissions.</p><p>Database migrations and maintenance tasks should work similarly.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7ed30dd63a4e" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Integrating Keycloak Authentication with Spring Boot: A Complete Guide]]></title>
            <link>https://medium.com/@iaravinda33/integrating-keycloak-authentication-with-spring-boot-a-complete-guide-98df2c8d244a?source=rss-6397f9c14ff1------2</link>
            <guid isPermaLink="false">https://medium.com/p/98df2c8d244a</guid>
            <category><![CDATA[spring-security]]></category>
            <category><![CDATA[authentication]]></category>
            <category><![CDATA[keycloak]]></category>
            <category><![CDATA[docker-compose]]></category>
            <category><![CDATA[spring-boot]]></category>
            <dc:creator><![CDATA[Isuru Aravinda]]></dc:creator>
            <pubDate>Wed, 18 Sep 2024 17:13:54 GMT</pubDate>
            <atom:updated>2024-09-19T03:07:15.787Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*UmGrfhebu8faubLIn-8RbQ.jpeg" /></figure><h3>Introduction</h3><p>In modern applications, handling authentication and authorization securely is a critical requirement. Keycloak, an open-source Identity and Access Management (IAM) tool, simplifies the process of integrating authentication with various applications, including Spring Boot. In this guide, we’ll walk through how to configure Keycloak as the authentication provider for a Spring Boot application.</p><h4><strong>Prerequisites</strong></h4><ol><li><a href="https://www.jetbrains.com/idea/">IntelliJ IDEA</a></li><li><a href="https://www.docker.com/products/docker-desktop/">Docker Desktop</a></li><li><a href="https://www.postman.com/downloads/">Postman</a></li></ol><h4><strong>I’ll be using</strong></h4><ul><li><a href="https://start.spring.io/#!type=maven-project&amp;language=java&amp;platformVersion=3.3.3&amp;packaging=jar&amp;jvmVersion=22&amp;groupId=com.rkisuru&amp;artifactId=keycloak-app&amp;name=keycloak-app&amp;description=Keycloak%20demo%20app&amp;packageName=com.rkisuru.keycloak.app&amp;dependencies=web,oauth2-resource-server,security">Java 22</a></li><li><a href="https://start.spring.io/#!type=maven-project&amp;language=java&amp;platformVersion=3.3.3&amp;packaging=jar&amp;jvmVersion=22&amp;groupId=com.rkisuru&amp;artifactId=keycloak-app&amp;name=keycloak-app&amp;description=Keycloak%20demo%20app&amp;packageName=com.rkisuru.keycloak.app&amp;dependencies=web,oauth2-resource-server,security">Spring boot 3.3.3</a></li><li><a href="https://www.keycloak.org/">Keycloak 25.0.5</a></li></ul><h3>You’ll learn how to:</h3><ul><li>Initialize a Spring Boot project</li><li>Set up and run Keycloak by using Docker Compose</li><li>Configure Keycloak for authentication and role-based access control</li><li>Configure Spring Boot application for Keycloak authentication</li><li>Test the authentication flow using Postman</li></ul><h4>1. Initializing the Spring Boot Project</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*UwwRMolJZEzlw8vkp2h_yQ.png" /></figure><p>The first step is to set up the Spring Boot project. Use the Spring Initializr (or your preferred method) to generate a project with the necessary dependencies, including <strong>Spring Web</strong>, <strong>Spring Security</strong>, and <strong>Spring Boot Starter OAuth2 Resource Server</strong>. <a href="https://start.spring.io/#!type=maven-project&amp;language=java&amp;platformVersion=3.3.3&amp;packaging=jar&amp;jvmVersion=22&amp;groupId=com.rkisuru&amp;artifactId=keycloak-app&amp;name=keycloak-app&amp;description=Keycloak%20demo%20app&amp;packageName=com.rkisuru.keycloak.app&amp;dependencies=web,oauth2-resource-server,security"><strong><em>or use this link to download the project</em></strong></a><em>.</em></p><p>Once you download the project extract it your preferred location and open the project using your IDE.</p><h4>2. Setting up Keycloak with Docker and Docker-Compose</h4><p><em>Note: Running Keycloak locally can be simplified using Docker Compose. By containerizing these services, you can ensure a consistent environment for development and testing.</em></p><ol><li>Start Docker Desktop.</li><li>In your project directory, create a new file named <strong>docker-compose.yml</strong>.</li><li>Open the <strong>docker-compose.yml</strong> file and add the following lines:</li></ol><pre>services:<br>  keycloak:<br>    container_name: keycloak_demo<br>    image: quay.io/keycloak/keycloak:25.0.5<br>    ports:<br>      - 9090:8080<br>    environment:<br>      KEYCLOAK_ADMIN: admin<br>      KEYCLOAK_ADMIN_PASSWORD: password<br>    volumes:<br>      - keycloak_data:/opt/keycloak/data<br>    command:<br>      - &#39;start-dev&#39;<br><br>volumes:<br>  keycloak_data:</pre><p>Now it will look like this in your IDE,</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*CGneV3KzQbg0mC0WA0vy5w.jpeg" /></figure><p><em>Note: To ensure that Keycloak data persists even after restarting the container, it’s important to specify </em><strong><em>volumes</em></strong><em>. Without these, all Keycloak data would be lost when the container is restarted. Additionally, since the default port for the Tomcat server is 8080, I’ve configured Keycloak to run on port 9090 to avoid conflicts</em></p><p>4. Now open the terminal in the exact directory and run the following command</p><p><strong><em>docker-compose up</em></strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/964/1*xnuGpW3sfr6rz3-izEBPtA.jpeg" /></figure><blockquote>Note: If the Keycloak image is not already available locally, Docker will automatically pull it when you run the container</blockquote><p>5. Once it is done you can check the running containers by opening up a new terminal and running following command</p><p><strong><em>docker ps</em></strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*nFahIOOduWY9lq8cyDjUVQ.jpeg" /></figure><p>As you can see now the container is up and running.</p><h4>3. Configuring Keycloak for Authentication</h4><ol><li>Navigate to <strong>localhost:9090</strong> in your browser. Sign up by providing the username and password specified in the Docker Compose file. This will take you to the Keycloak Admin Console.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*lTxn8RQgtI3WjW-IG8Rx7g.png" /></figure><p>2. Create a Realm</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*eom5q_2_OvWFPVBkZVlDMg.jpeg" /></figure><p>3. Create a Client</p><p>Create a new client by specifying the client ID, name, and description.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*GHpvxexpU4RVg-caQykAuQ.jpeg" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*NAD4T5XwQ-ircgEM9CPhsQ.jpeg" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*d9dr7Kid9q9hOPN0dp4jkw.jpeg" /></figure><blockquote>Note: For the integration, we need to set the Web Origins to allow communication between Keycloak and our Spring Boot application. To do this, we will set the Web Origins of our Keycloak client to <strong>http://localhost:8080/*</strong>, where our Spring Boot application is running. Alternatively, if you want to allow more flexibility, you can use a wildcard (<strong>*</strong>) to permit access from any origin. However, I recommend specifying the exact origin whenever possible to avoid potential security risks. Keep all other settings as they are !</blockquote><p>4. Creating Users</p><p>i. Add Users:</p><ul><li>Navigate to the Users section in the Keycloak Admin Console.</li><li>Create three users as <strong>admin</strong>, <strong>user</strong>, and <strong>admin_user</strong>.</li><li>For each user, ensure that you fill out all the fields and make sure to check <strong>Email verified</strong> option.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*JkyYgPOppQWsbpgKFwWV0Q.jpeg" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*iu5NLOiK0Hwl75ItVo6SjA.jpeg" /></figure><p>ii. Set User Passwords:</p><ul><li>After creating each user, navigate to the Credentials tab.</li><li>Set a password for each user and uncheck the <strong>Temporary</strong> option.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*A3CYXd98DjtcoeRT_fTWag.jpeg" /></figure><p>5. Creating <strong>Client</strong> and <strong>Realm</strong> roles</p><p>i. <strong>Client roles:</strong></p><p>Start by creating client roles in Keycloak. Navigate to your client and add two new roles as <strong>role_admin</strong> and <strong>role_user</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*CFggyXOgHMgBZyrw2v_RPQ.jpeg" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*D1NdWbh1SxExeR9xeqJOYQ.jpeg" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*CMOghAvOle6rPzoxEapbAA.jpeg" /></figure><p>ii. <strong>Realm roles:</strong> Next, navigate to “<strong>Realm roles</strong>” and create two roles as <strong>admin</strong> and <strong>user</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*WuwVs9a6eryBoKrDtl7YNg.jpeg" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*uwdp_o590O_xzr7JuiiItw.jpeg" /></figure><p>iii. <strong>Making Realm roles Composite:</strong> To assign client roles to these realm roles, follow these steps:</p><ul><li>Go to “<strong>Roles</strong>” and select the <strong>admin</strong> realm role.</li><li>In the “<strong>Associated roles</strong>” tab, click “<strong>Assign role</strong>.”</li><li>Select “<strong>Filter by clients</strong>” to view the client roles, check the <strong>role_admin</strong> client role, and assign it.</li><li>Repeat the process for the <strong>user</strong> realm role and assign <strong>role_user</strong> to it.</li><li>After these steps, both the <strong>admin </strong>and <strong>user </strong>realm roles should have their “<strong>Composite</strong>” attribute set to <strong>true</strong>, indicating that they are composite roles.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*B8muygzzhusjBCYUFERbdQ.jpeg" /></figure><p>6. Assign Roles to Users</p><ul><li>Now navigate to <strong>Users</strong> section and select <strong>admin </strong>and then select <strong>Role mapping</strong>, select <strong>Assign role -&gt; Filter by clients</strong> and assign <strong>role_admin</strong>.</li><li>Repeat the process and assign <strong>role_user</strong> to <strong>user</strong> and for the <strong>admin_user</strong> make sure to assign both <strong>role_user</strong> and <strong>role_admin</strong>.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-RHfZcztHawR0PhfagpPwQ.jpeg" /></figure><h4>4. Obtaining the token for the users using Postman</h4><p>Now let’s move on to obtaining the token.</p><p>When you go to the <strong>Realm settings</strong> section on the sidebar you will see the<strong><em><br>“</em>OpenID Endpoint Configuration<em>”</em></strong> link:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*49vPXd5JDzjDjuhpYa9u4g.jpeg" /></figure><p>Just copy “<strong>token_endpoint</strong>” value:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*pPHxT6PId_DgORe00y30cQ.jpeg" /></figure><p>We can now send a <strong>POST</strong> request to this endpoint to get a token. We can use one of the users we created as the credentials. I use <strong>Postman</strong> for this request:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*FncOSJWyS9YlP-0I40yTDg.jpeg" /></figure><p>Create a new collection and create <strong>POST </strong>requests for each user.</p><p>Paste the token endpoint URL.</p><p>Select <strong>Body</strong> -&gt; <strong>x-www-form-urlencoded</strong> and enter corresponding values;</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*sNGNm8BhQzs345-H9Q4-eg.jpeg" /></figure><p>When you configure the settings indicated in the image, you will be able to obtain the access token.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*piQnRgGgM09v7q7tpwylPw.jpeg" /></figure><h4>5. Configuring Spring Boot application</h4><ol><li>application.yml</li></ol><p>Rename the <strong>application.properties</strong> file in the <strong>src/main/resources</strong> directory to <strong>application.yml</strong>. Then, clear its contents and replace them with the following configuration:</p><pre>spring:<br>  security:<br>    oauth2:<br>      resourceserver:<br>        jwt:<br>          issuer-uri: http://localhost:9090/realms/realm-demo<br>          jwk-set-uri: http://localhost:9090/realms/realm-demo/protocol/openid-connect/certs<br><br>logging:<br>  level:<br>    org:<br>      springframework:<br>        security: DEBUG<br><br>jwt:<br>  auth:<br>    converter:<br>      resource-id: demo<br>      principle-attribute: preferred_username</pre><ul><li><strong>spring.security.oauth2.resourceserver.jwt.issuer-uri</strong>: This setting specifies the <strong>Issuer URI</strong> for JWT authentication. It includes the URI of the Keycloak realm.</li><li><strong>spring.security.oauth2.resourceserver.jwt.jwk-set-uri</strong>: Specifies the JWK set URI at the location where JWT will be used. This URI is used to fetch public keys.</li><li><strong>jwt.auth.converter.resource-id</strong>: Specifies the resource ID of the JWT. Typically, it includes a client identifier.</li><li><strong>jwt.auth.converter.principal-attribute</strong>: Specifies a specific attribute name in the JWT&#39;s header (such as <strong>principal_username</strong>) where principals (users) are indicated.SecurityConfig class</li></ul><p>2. Creating a custom JWT to Authentication Token Converter</p><p>Create a new package named <strong>config</strong> and then add a new class called <strong>JwtConverter</strong> within this package.</p><p>Add the following code to the <strong>JwtConverter</strong> class:</p><pre>@Component<br>public class JwtConverter implements Converter&lt;Jwt, AbstractAuthenticationToken&gt; {<br><br>    private final JwtGrantedAuthoritiesConverter jwtGrantedAuthoritiesConverter =<br>            new JwtGrantedAuthoritiesConverter();<br><br>    @Value(&quot;${jwt.auth.converter.principle-attribute}&quot;)<br>    private String principleAttribute;<br>    @Value(&quot;${jwt.auth.converter.resource-id}&quot;)<br>    private String resourceId;<br><br>    @Override<br>    public AbstractAuthenticationToken convert(@NonNull Jwt jwt) {<br><br>        Collection&lt;GrantedAuthority&gt; authorities = Stream.concat(<br>                jwtGrantedAuthoritiesConverter.convert(jwt).stream(),<br>                extractResourceRoles(jwt).stream()<br>        ).collect(Collectors.toSet());<br><br>        return new JwtAuthenticationToken(<br>                jwt,<br>                authorities,<br>                getPrincipleClaimName(jwt)<br>        );<br>    }<br><br>    private String getPrincipleClaimName(Jwt jwt) {<br>        String claimName = JwtClaimNames.SUB;<br>        if (principleAttribute != null) {<br>            claimName = principleAttribute;<br>        }<br>        return jwt.getClaim(claimName);<br>    }<br><br>    private Collection&lt;? extends GrantedAuthority&gt; extractResourceRoles(Jwt jwt) {<br>        Map&lt;String, Object&gt; resourceAccess;<br>        Map&lt;String, Object&gt; resource;<br>        Collection&lt;String&gt; resourceRoles;<br>        if (jwt.getClaim(&quot;resource_access&quot;) == null) {<br>            return Set.of();<br>        }<br>        resourceAccess = jwt.getClaim(&quot;resource_access&quot;);<br><br>        if (resourceAccess.get(resourceId) == null) {<br>            return Set.of();<br>        }<br>        resource = (Map&lt;String, Object&gt;) resourceAccess.get(resourceId);<br><br>        resourceRoles = (Collection&lt;String&gt;) resource.get(&quot;roles&quot;);<br><br>        return resourceRoles<br>                .stream()<br>                .map(role -&gt; new SimpleGrantedAuthority(&quot;ROLE_&quot; + role))<br>                .collect(Collectors.toSet());<br>    }<br>}</pre><p>The <strong>JwtConverter</strong> class in Spring Boot converts JWT tokens from Keycloak into Spring Security authentication tokens. It uses <strong>JwtGrantedAuthoritiesConverter</strong> to handle standard JWT scopes and also extracts additional resource-specific roles from the JWT.</p><ul><li><strong>Custom Properties</strong>: It leverages properties like <strong>principle-attribute</strong> for setting the principal claim and <strong>resource-id</strong> for identifying the Keycloak client. For <strong>principle-attribute</strong> and <strong>resource-id</strong>, we use values stored in the <strong>application.yml</strong></li><li><strong>Authority Extraction</strong>: Combines roles from both the standard JWT claims and resource-specific roles into a single set of <strong>GrantedAuthority</strong> objects.</li><li><strong>Principal Claim</strong>: The principal for the authentication token is typically derived from the <strong>sub</strong> claim but can be configured.</li></ul><p>3. Implementing Security Configuration using Spring Security</p><p>Create a new class named <strong>SecurityConfig</strong> in the <strong>config</strong> package and add the following code to it:</p><pre>@Configuration<br>@EnableWebSecurity<br>@EnableMethodSecurity<br>public class SecurityConfig{<br><br>    @Autowired<br>    private JwtConverter jwtConverter;<br><br>    @Bean<br>    public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {<br><br>        http<br>                .csrf(AbstractHttpConfigurer::disable)<br>                .authorizeHttpRequests((authorize)-&gt; authorize<br>                        .anyRequest().authenticated())<br>                .oauth2ResourceServer(<br>                        (oauth2)-&gt; oauth2.jwt(<br>                                jwt-&gt; jwt.jwtAuthenticationConverter(jwtConverter)<br>                        ))<br>                .sessionManagement(<br>                        session-&gt; session.sessionCreationPolicy(<br>                                SessionCreationPolicy.STATELESS)<br>                );<br><br>        return http.build();<br>    }<br>}</pre><p>The <strong>SecurityConfig</strong> class sets up security for the Spring Boot application. It disables CSRF protection, requires authentication for all requests, and configures the application to use JWTs for OAuth2 resource server support. Sessions are managed in a stateless manner, meaning no session state is maintained between requests. This setup ensures that all incoming requests are authenticated using JWT tokens.</p><ul><li><strong>Dependency Injection</strong>: The <strong>JwtConverter</strong> is injected into the configuration using <strong>@Autowired</strong>. This component is responsible for converting JWT tokens.</li><li><strong>OAuth2 Resource Server</strong>: The application is configured to use OAuth2 for resource server support. This setup includes specifying that JWT (JSON Web Tokens) should be used for authentication, with the <strong>jwtAuthenticationConverter</strong> set to our <strong>JwtConverter</strong> instance.</li></ul><h4>6. Creating the endpoints</h4><p>Create a package named <strong>controller</strong> and add a class called <strong>Controller</strong> within it. Include the following code in the <strong>Controller</strong> class:</p><pre>import org.springframework.http.ResponseEntity;<br>import org.springframework.security.access.prepost.PreAuthorize;<br>import org.springframework.web.bind.annotation.GetMapping;<br>import org.springframework.web.bind.annotation.RequestMapping;<br>import org.springframework.web.bind.annotation.RestController;<br><br>@RestController<br>@RequestMapping(&quot;/api/v1&quot;)<br>public class Controller {<br><br>    @GetMapping<br>    public ResponseEntity&lt;String&gt; hello() {<br>        return ResponseEntity.ok(&quot;Hello!&quot;);<br>    }<br><br>    @GetMapping(&quot;/user&quot;)<br>    @PreAuthorize(&quot;hasRole(&#39;role_user&#39;)&quot;)<br>    public ResponseEntity&lt;String&gt; helloUser() {<br>        return ResponseEntity.ok(&quot;Hello From User!&quot;);<br>    }<br><br>    @GetMapping(&quot;/admin&quot;)<br>    @PreAuthorize(&quot;hasRole(&#39;role_admin&#39;)&quot;)<br>    public ResponseEntity&lt;String&gt; helloAdmin() {<br>        return ResponseEntity.ok(&quot;Hello From Admin!&quot;);<br>    }<br>}</pre><p>In this setup, the first endpoint is accessible to all authenticated users, the second endpoint is reserved to users with the role <strong>role_user</strong>, and the third endpoint is reserved for users with the role <strong>role_admin</strong>.</p><p><em>Note: The </em><strong><em>admin_user</em></strong><em> is assigned both the </em><strong><em>role_user</em></strong><em> and </em><strong><em>role_admin</em></strong><em> roles, allowing them to access all endpoints.</em></p><p><strong>Final Project Structure will look like this:</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/456/1*ia5iypRb3DpgOV89Nx42bQ.jpeg" /></figure><p><strong>SPECIAL NOTE !</strong></p><blockquote>Obtain a token for the user using postman and go to <a href="https://jwt.io/"><strong>https://jwt.io/</strong></a> website and paste your token.</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*N_L4X2rFOhR1ZQoAApFKWQ.jpeg" /></figure><blockquote>You can see<strong> “roles”: [ “role_user” ] as a key , value pair.</strong></blockquote><blockquote>We extract this “<strong>roles</strong>” using <strong>extractResourceRoles</strong> method in <strong>JwtConverter</strong> class.</blockquote><blockquote>And in Controller class we make sure only user can access <a href="http://localhost:8080/api/v1/user"><strong>http://localhost:8080/api/v1/user</strong></a> endpoint by adding <strong>@PreAuthorize(“hasRole(‘role_user’)”)</strong>.</blockquote><h4>7. Testing the Authentication flow using Postman</h4><ul><li>1st make sure the <strong>Spring Boot application</strong> and the <strong>keycloak_demo</strong> <strong>container</strong> up and running.</li><li>Let’s start the postman and create new <strong>GET</strong> requests for <strong>user</strong>, <strong>admin</strong>, and <strong>admin_user</strong>.</li><li>Obtain an access token for the user.</li><li>Enter the endpoint URL for user in the field and select <strong>Authorization to Bearer Token</strong>.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-7OSIl6k_J33A1c0kZg_Iw.jpeg" /></figure><ul><li>Paste token in the token field and send the request and you will see the “<strong>200 OK</strong>” response “ <strong>Hello From User!</strong> ”.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Nc3Z3LnFyhinRY_95pym1g.jpeg" /></figure><ul><li>Now let’s change the <a href="http://localhost:8080/api/v1/user">http://localhost:8080/api/v1/<strong>user</strong></a> to <a href="http://localhost:8080/api/v1/admin">http://localhost:8080/api/v1/<strong>admin</strong></a> send the request.</li><li>As you can see we get <strong>403 error</strong> as the response. This is because <a href="http://localhost:8080/api/v1/admin">http://localhost:8080/api/v1/<strong>admin</strong></a><strong> </strong>is reserved for the <strong>admin</strong>.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*pK9ceYQpzMDwT4CPj3zpmA.jpeg" /></figure><ul><li>Just play around as see if the application is working properly.</li></ul><p>That’s all!</p><h3>Conclusion</h3><p>Integrating Keycloak with Spring Boot provides a secure authentication and authorization system. By using Docker Compose, we simplified the setup process. With Keycloak managing roles and users, and Spring Boot enforcing security through custom configurations, we created a scalable solution for handling role-based access in our Spring Boot application.</p><p>Thank you for your precious time !</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=98df2c8d244a" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>