<?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 Syed Abdullah on Medium]]></title>
        <description><![CDATA[Stories by Syed Abdullah on Medium]]></description>
        <link>https://medium.com/@syedabdullahrahman?source=rss-4ca5c46c8f8f------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*F7ey0PyuClafPmbq3iMyRg.jpeg</url>
            <title>Stories by Syed Abdullah on Medium</title>
            <link>https://medium.com/@syedabdullahrahman?source=rss-4ca5c46c8f8f------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Fri, 20 Nov 2026 14:56:37 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@syedabdullahrahman/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[Mastering REST API Design: Essential Best Practices, Do’s and Don’ts for 2026]]></title>
            <link>https://medium.com/@syedabdullahrahman/mastering-rest-api-design-essential-best-practices-dos-and-don-ts-for-2024-dd41a2c59133?source=rss-4ca5c46c8f8f------2</link>
            <guid isPermaLink="false">https://medium.com/p/dd41a2c59133</guid>
            <category><![CDATA[rest-api-best-practices]]></category>
            <category><![CDATA[api-development]]></category>
            <category><![CDATA[mastering-rest-api]]></category>
            <category><![CDATA[rest-api-design]]></category>
            <category><![CDATA[api]]></category>
            <dc:creator><![CDATA[Syed Abdullah]]></dc:creator>
            <pubDate>Sun, 01 Sep 2024 19:17:44 GMT</pubDate>
            <atom:updated>2026-01-10T19:55:14.038Z</atom:updated>
            <content:encoded><![CDATA[<h3>What we will Learn from This Article 🚀</h3><h4><strong>👉 Fundamental Principles of REST APIs</strong></h4><ul><li>Core concept of RESTful Architechture</li><li>Key HTTP methods and their appropiate uses</li></ul><h4>👉<strong> Best Practices for API design</strong></h4><ul><li>How to design meaningful and efficient resource-oriented URLs.</li><li>The importance of using standard HTTP status codes correctly.</li><li>Techniques for implementing filtering, sorting, and pagination.</li><li>The need for clear, consistent API documentation and tools to aid in this.</li><li>Effective strategies for API versioning to ensure backward compatibility.</li><li>Best practices for securing APIs, including authentication and HTTPS.</li><li>How to handle errors in a way that’s user-friendly and informative.</li><li>Practical tips for maintaining RESTful principles and avoiding common mistakes.</li><li>Insights into designing scalable and intuitive APIs.</li><li>Common pitfalls in API design and how to avoid them.</li></ul><h4>👉 Practical Do’s and Don’ts</h4><ul><li>Practical tips for maintaining RESTful principles and avoiding common mistakes.</li><li>Insights into designing scalable and intuitive APIs.</li><li>Common pitfalls in API design and how to avoid them.</li></ul><h3>What are APIs ?</h3><blockquote>An application programming interface (API) is a set of tools, definitions, and protocols for integrating application software and services. It’s the stuff that lets your products and services communicate with other products and services without having to constantly build new connectivity infrastructure.</blockquote><blockquote>APIs can be private (for internal use only), partnered (shared with specific partners to provide additional revenue streams), or public (allowing third parties to develop apps that interact with your API to foster innovation).</blockquote><blockquote><a href="https://www.redhat.com/en/topics/api/what-is-a-rest-api">https://www.redhat.com/en/topics/api/what-is-a-rest-api</a></blockquote><h3>What is a REST API ?</h3><blockquote>A REST API (also known as RESTful API) is an application programming interface (API or web API) that conforms to the constraints of REST architectural style and allows for interaction with RESTful web services. REST stands for representational state transfer and was created by computer scientist Roy Fielding.</blockquote><blockquote><a href="https://www.redhat.com/en/topics/api/what-is-a-rest-api">https://www.redhat.com/en/topics/api/what-is-a-rest-api</a></blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/826/1*qfgAiAL800Zs7enSjI1KTw.jpeg" /></figure><h3>REST API architectural constraints</h3><p>REST is a set of architectural constraints, not a protocol or a standard. Here are the constraints to be an ideal RESTful API:</p><ol><li><strong>Client-server architecture</strong>: A client-server architecture made up of clients, servers, and resources, with requests managed through HTTP. Servers and clients may also be replaced and developed independently (also in different programming language) as long as the interface between them is not altered.</li><li><strong>Stateless</strong>: In client-server communication, no data should be stored on the server during the processing of the request transfer. Meaning no client information is stored between requests and each request is separate and unconnected.</li><li><strong>Cacheable</strong>: The client should have the ability to store responses in a cache. This greatly improves the performance of the API.</li><li><strong>Layered System</strong>: The server can have multiple layers for implementation. This layered architecture helps to improve scalability by enabling load balancing.</li><li><strong>Code on Demand: </strong>This constraint is <strong><em>optional</em></strong>. This constraint indicates that the functionality of the client applications can be extended at runtime by allowing a code download from the server and executing the code.</li><li><strong>Uniform Interface:</strong> The uniform interface constraint is <strong>fundamental </strong>to the design of any RESTful system. It <strong>simplifies </strong>and <strong>decouples </strong>the architecture, which enables each part to evolve independently.</li></ol><blockquote>The <strong>four </strong>constraints for this uniform interface are:</blockquote><blockquote><strong>1. Resource identification in requests</strong>: Individual resources are identified in requests using URIs. The resources themselves are conceptually separate from the representations that are returned to the client. For example, the server could send data from its database as HTML, XML or as JSON — none of which are the server’s internal representation.</blockquote><blockquote><strong>2. Resource manipulation through representations</strong>: When a client holds a representation of a resource, including any metadata attached, it has enough information to modify or delete the resource’s state.</blockquote><blockquote><strong>3. Self-descriptive messages:</strong> Each message includes enough information to describe how to process the message. For example, which parser to invoke can be specified by a media type.</blockquote><blockquote><strong>4. Hypermedia as the engine of application state (HATEOAS) </strong>— Having accessed an initial URI for the REST application — analogous to a human Web user accessing the home page of a website — a REST client should then be able to use server-provided links dynamically to discover all the available resources it needs. As access proceeds, the server responds with text that includes hyperlinks to other resources that are currently available. There is no need for the client to be hard-coded with information regarding the structure of the server.</blockquote><blockquote>Source: <a href="https://en.wikipedia.org/wiki/REST#Uniform_interface">https://en.wikipedia.org/wiki/REST#Uniform_interface</a></blockquote><h3>What is a Resource?</h3><blockquote><em>The key abstraction of information in </em><strong><em>REST </em></strong><em>is a </em><strong><em>resource</em></strong><em>. Any information that can be named, can be a resource: </em><strong>a document</strong><em> or </em><strong>image</strong><em>, </em><strong>a temporal service</strong><em> (e.g. “today’s weather in Los Angeles”), </em><strong>a collection of other resources </strong><em>(e.g. “today’s top selling </em><strong>products</strong><em>” which is collection of </em><strong>product </strong><em>resources), </em><strong>a non-virtual object</strong><em> (e.g. a person), and so on.</em></blockquote><blockquote><em>— </em><a href="http://www.ics.uci.edu/~fielding/pubs/dissertation/rest_arch_style.htm#sec_5_2_1_1"><em>Roy Fielding’s dissertation</em></a></blockquote><h4>Singleton and Collection Resources</h4><p>A <strong>resource can be a singleton or a collection</strong>.</p><p>For example, “<strong>customers”<em> </em></strong>is a collection resource and “<strong>customer” </strong>is a singleton resource.</p><p>We can identify “<strong>customers” </strong>collection resource using the URI <strong>/customers</strong>. We can identify a single “<strong>customer” </strong>resource using the URI <strong>/customers/{customerId}</strong></p><pre>/customers       //  is a collection resource<br><br>/customers/{id}  //  is a singleton resource</pre><h4>Collection and Sub-collection Resources</h4><p>A <strong>resource may contain sub-collection resources</strong> also.</p><p>For example, sub-collection resource “<strong>accounts” </strong>of a particular “<strong>customer” </strong>can be identified using /customers/{customerId}/accounts</p><p>Similarly, a singleton resource “<strong>account” </strong>inside the sub-collection resource “<strong>accounts” </strong>can be identified /customers/{customerId}/accounts/{accountId}</p><pre>/customers      //is a collection resource<br><br>/customers/{id}/accounts  // is a sub-collection resource (customer&#39;s account)<br><br>/customers/{customerId}/accounts/{accountId} //a singleton resource (customer&#39;s specific account)</pre><h3>URI (Uniform Resource Identifiers)</h3><p>URI stands for <a href="https://en.wikipedia.org/wiki/Uniform_Resource_Identifier">Uniform Resource Identifiers</a> (URIs). It identifies a logical or physical resource on the web. URL and URN are subtypes of URI. URL locates a resource, while URN names a resource.</p><p>REST APIs use URI to address resources. REST API designers should create URIs that convey a REST API’s resource model to the potential clients of the API. When resources are named well, an API is intuitive and easy to use. If done poorly, that same API can be challenging to use and understand.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9bC0lXDqfAgDsg87EOVAOw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*fO-Go68P4nsL0jkCA3wTFg.png" /><figcaption>Differences between URI VS URL (Credit: <a href="https://refine.dev/blog/uri-vs-url/#introduction">https://refine.dev/blog/uri-vs-url/#introduction</a>)</figcaption></figure><h3><strong>Best Practices : </strong>Do’s and Don’ts</h3><h4>1. Use Proper HTTP Methods (Verbs) defining API operations</h4><p>The <strong>HTTP protocol</strong> defines a number of methods that assign semantic meaning to a request. The common HTTP methods used by most RESTful web APIs are:</p><ul><li><strong>GET </strong><em>retrieves a representation of the resource at the specified URI</em><br>The body of the response message contains the details of the requested resource.</li><li><strong>POST </strong><em>creates a new resource at the specified URI</em><br>The body of the request message provides the details of the new resource. <em>Note</em>: <strong>POST </strong>can also be used to trigger operations that don’t actually create resources.</li><li><strong>PUT </strong><em>either creates or replaces the resource at the specified URI</em><br>The body of the request message specifies the resource to be created or updated.</li><li><strong>PATCH </strong><em>performs a partial update of a resource<br></em>The request body specifies the set of changes to apply to the resource.</li><li><strong>DELETE </strong><em>removes the resource at the specified URI</em></li></ul><p>The effect of a specific request should depend on whether the resource is a collection or an individual item. The following table summarizes the common conventions adopted by most RESTful implementations using the e-commerce example.</p><p><strong>NOTE</strong>: <em>Not all of these requests might be implemented — it depends on the specific scenario</em>.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/440e04b93926e1bf89d592baad1f075d/href">https://medium.com/media/440e04b93926e1bf89d592baad1f075d/href</a></iframe><p>The differences between <strong>POST</strong>, <strong>PUT</strong>, and <strong>PATCH </strong>can be confusing.</p><ul><li>A <strong>POST </strong><em>request </em><strong><em>creates </em></strong><em>a resource and add to the resource collection</em>. The returns that newly created resource URI to the client. A <strong>POST </strong>request can also be used to submit data for processing to an existing resource, without any new resource being created.</li><li>A <strong>PUT </strong><em>request </em><strong><em>creates </em></strong><em>a resource or </em><strong><em>updates </em></strong><em>an existing resource</em>. The request body contains a complete representation of the resource. If a resource with this URI already exists, it is replaced. Otherwise a new resource is created, if the server supports doing so. <strong>PUT </strong>requests are most frequently applied to resources that are individual items, such as a specific customer, rather than collections. A server might support <strong>updates </strong>but not creation via <strong>PUT</strong>. Whether to support creation via <strong>PUT </strong>depends on whether the client can meaningfully assign a URI to a resource before it exists. If not, then use <strong>POST </strong>to <strong>create </strong>resources and <strong>PUT </strong>or <strong>PATCH </strong>to update.</li><li>A <strong>PATCH </strong><em>request performs a</em><strong><em> partial update</em></strong><em> to an existing resource</em>. The request body specifies a set of <em>changes</em> to apply to the resource. This can be more efficient than using <strong>PUT</strong>, because the client only sends the changes, not the entire representation of the resource.</li></ul><p><strong>PUT </strong>requests must be <strong><em>idempotent</em></strong>. If a client submits the same <strong>PUT </strong>request multiple times, the results should always be the same (the same resource will be modified with the same values). <strong>POST </strong>and <strong>PATCH</strong> requests are not guaranteed to be <strong><em>idempotent</em></strong>.</p><h4>2. Use nouns (plural nouns) to represent resources</h4><p>RESTful URI should refer to a resource that is a thing (noun) instead of referring to an action (verb) because nouns have properties that verbs do not have — similarly, resources have attributes. Some examples of a resource are:</p><ul><li>Users</li><li>Accounts</li></ul><p>and their resource URIs can be designed as below:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/1f1942ae1bea0624a03c397d8a97c10d/href">https://medium.com/media/1f1942ae1bea0624a03c397d8a97c10d/href</a></iframe><h4><strong>3. </strong>Use Sub-Resources for Relations</h4><p>Use consistent resource naming conventions and URI formatting for minimum ambiguity and maximum readability and maintainability. Implementing the below design hints to achieve consistency:</p><ul><li>In REST, the relationships are often modeled by a <strong>sub-resource</strong>. Use the following pattern for <strong>sub-resources</strong>.</li></ul><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/3772e7cbb93ac1fb7a8e168b51eb628c/href">https://medium.com/media/3772e7cbb93ac1fb7a8e168b51eb628c/href</a></iframe><h4>4. Focus on Readablity and Consistency</h4><ul><li>Do not use trailing forward slash (/) in URIs</li></ul><pre>GET /device-management/managed-devices/ <br>GET /device-management/managed-devices       /*This is much better version*/</pre><ul><li>Use hyphens (-) and Kebab-case (some-var-name) to improve the readability of URIs</li></ul><pre>GET   /devicemanagement/manageddevices/<br>GET   /device-management/managed-devices  /*This is much better version*/<br><br>GET   /my-folder/my-doc    // Good<br>GET   /MY-FOLDER/my-doc    // Avoid<br>GET   /My-Folder/my-doc    // Avoid</pre><ul><li>Avoid underscore ( _ ) and Camel-case (someVarName) Snake-case (some_var_name) Pasal-case (SomeVarName)</li></ul><pre>GET /managed-entities/{id}/install-script-location  //More readable<br><br>GET /managed_entities/{id}/install_Script_Location  //Snake-case - readable but not conventional<br><br>GET /managedEntities/{id}/installScriptLocation  //Camel-case - Less readable</pre><ul><li>Do not use file extensions</li></ul><pre>/device-management/managed-devices.xml  /*Do not use it*/<br><br>/device-management/managed-devices      /*This is correct URI*/</pre><ul><li>Never use <strong>CRUD </strong>function names in URIs</li></ul><pre>/*     Avoid  */<br><br>HTTP GET     /get-managed-devices     <br>HTTP POST    /create-managed-devices<br><br><br>/*     Good   */<br><br>HTTP GET     /managed-devices         //  Get all devices<br>HTTP POST    /managed-devices         //  Create new Device<br><br>HTTP GET     /managed-devices/{id}    //  Get device for given Id<br>HTTP PUT     /managed-devices/{id}    //  Update device for given Id<br>HTTP DELETE  /managed-devices/{id}    //  Delete device for given Id</pre><ul><li>Do not Use Verbs in the URI</li></ul><pre>GET    /scripts/{id}/execute   //DON&#39;t DO THIS! - It is RPC, and not REST<br><br>POST   /scripts              //Better: Create a script using POST action<br><br>GET    /scripts/{id}/status   //check the execution status<br></pre><h4>5. Use HTTP Response Status Codes</h4><p>Always use regular HTTP status codes in responses to requests made to the API. This will help the users to know what is going on — whether the request is successful, or if it fails, or something else.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ab69461850e6f8329eb49ed77468920c/href">https://medium.com/media/ab69461850e6f8329eb49ed77468920c/href</a></iframe><h4><strong>6. Use Filtering, Sorting, and Pagination to Retrieve the Data Requested</strong></h4><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/82275ad7d48bf5361bafc989842df7b2/href">https://medium.com/media/82275ad7d48bf5361bafc989842df7b2/href</a></iframe><h4>7. Use HATEOAS to enable navigation to related resources</h4><p><strong>HATEOAS </strong>(<em>Hypertext as the Engine of Application State</em>) is a principle of REST that allows clients to navigate resources and discover available operations solely through the hyperlinks provided in responses. This means that clients do not need prior knowledge of URIs; instead, each HTTP GET request returns the necessary information and links to related resources, enabling dynamic exploration of the API.</p><p>In the example resoponse/books/1 share navigatable <strong>links </strong>like /authors/1 /books/1/reviews</p><pre>{<br>  &quot;books&quot;: [<br>    {<br>      &quot;id&quot;: 1,<br>      &quot;title&quot;: &quot;The Great Gatsby&quot;,<br>      &quot;author&quot;: &quot;F. Scott Fitzgerald&quot;,<br>      &quot;links&quot;: {<br>        &quot;self&quot;: &quot;/books/1&quot;,<br>        &quot;author&quot;: &quot;/authors/1&quot;,<br>        &quot;reviews&quot;: &quot;/books/1/reviews&quot;<br>      }<br>    },<br>    {<br>      &quot;id&quot;: 2,<br>      &quot;title&quot;: &quot;To Kill a Mockingbird&quot;,<br>      &quot;author&quot;: &quot;Harper Lee&quot;,<br>      &quot;links&quot;: {<br>        &quot;self&quot;: &quot;/books/2&quot;,<br>        &quot;author&quot;: &quot;/authors/2&quot;,<br>        &quot;reviews&quot;: &quot;/books/2/reviews&quot;<br>      }<br>    }<br>  ]<br>}</pre><h4>8. Use SSL for Security</h4><p><strong>SSL (Secure Socket Layer)</strong> is essential for securing REST APIs, protecting them from malicious attacks. It ensures that communication between the server and client is private and that users can only access the data they are authorized to see.</p><p>We can tell if a REST API is secured with SSL by looking for https:// in the URL. For example, https://mysite.com/posts is secured with SSL, whereas http://mysite.com/posts is not.</p><h4>9. Provide Accurate API Documentation</h4><p>Good API documentation helps developers use our API correctly. It can make more people want to use our API and have a better time with it. A popular API documentation tool is <a href="https://www.openapis.org/">OpenAPI</a> (<a href="https://swagger.io/">Swagger</a>)</p><h4>10. Versioning a RESTful web API</h4><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/0cb87bdb7813ae530746502b5cf7f080/href">https://medium.com/media/0cb87bdb7813ae530746502b5cf7f080/href</a></iframe><h4>11. API security and access control</h4><p>Keeping our API safe and controlling who can use it are key parts of making a good RESTful API. Some ways to do this:</p><ul><li>Setting up <a href="https://oauth.net/2/"><strong>OAuth 2.0</strong></a> or <a href="https://en.wikipedia.org/wiki/JSON_Web_Token"><strong>JSON Web Tokens</strong></a><strong> (JWT)</strong> so that unauthenticated users can’t access</li><li><strong>API keys</strong> show who’s using. <strong>API Rate limits</strong> stop people from using it too much.</li><li>Implement <strong>Role-Based Access Control (RBAC) </strong>etc..</li></ul><h4>12. Don’t forget about API performance</h4><p>Making our API work better is key for happy users, lower costs, and easier growth.</p><ul><li>Effective <strong>caching</strong></li><li>Data <strong>compression </strong>methods</li><li><strong>Asynchronous </strong>processing</li><li>Handling <strong>batch operations</strong></li><li>Measuring API performance &amp; Analyzing API usage</li><li>Monitoring API health and uptime</li><li>Testing RESTful APIs (unit tests, integration tests, load tests,security tests) etc..</li></ul><h3>Conlusion</h3><p>A great REST API is built by following key rules and best practices.</p><p>By sticking to these rules, we’ll build APIs that are easy to use, reliable, and ready for the future.</p><p><strong><em>References:</em></strong></p><ol><li><a href="https://ics.uci.edu/~fielding/pubs/dissertation/rest_arch_style.htm#sec_5_2_1_1"><em>CHAPTER 5 : Representational State Transfer (REST)</em></a><em> (by </em><strong><em>Roy</em></strong><em> T. </em><strong><em>Fielding </em></strong><em>originator of the REST architectural style)</em></li><li><a href="https://www.redhat.com/en/topics/api"><em>Understanding APIs</em></a><em> (by </em><strong><em>Redhat</em></strong><em>)</em></li><li><a href="https://refine.dev/blog/uri-vs-url/#introduction"><em>The Important Differences between URI VS URL</em></a></li><li><a href="https://en.wikipedia.org/wiki/REST"><em>REST — Wikipedia</em></a></li><li><a href="https://learn.microsoft.com/en-us/azure/architecture/best-practices/api-design"><em>RESTful web API design</em></a><em> (by </em><strong><em>learn.microsoft.com</em></strong><em>)</em></li><li><a href="https://restfulapi.net/resource-naming/"><em>REST API URI Naming Conventions and Best Practices</em></a></li><li><a href="https://www.freecodecamp.org/news/rest-api-best-practices-rest-endpoint-design-examples/"><em>REST API Best Practices — REST Endpoint Design Examples</em></a></li><li><a href="https://daily.dev/blog/restful-api-design-best-practices-guide-2024"><em>RESTful API Design Best Practices Guide 2024</em></a></li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=dd41a2c59133" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Keycloak Angular integration : Securing  angular application step-by-step]]></title>
            <link>https://medium.com/@syedabdullahrahman/keycloak-angular-integration-securing-angular-application-step-by-step-bd185333a304?source=rss-4ca5c46c8f8f------2</link>
            <guid isPermaLink="false">https://medium.com/p/bd185333a304</guid>
            <category><![CDATA[keycloak]]></category>
            <category><![CDATA[security]]></category>
            <category><![CDATA[angular]]></category>
            <category><![CDATA[keycloak-integration]]></category>
            <category><![CDATA[oauth2]]></category>
            <dc:creator><![CDATA[Syed Abdullah]]></dc:creator>
            <pubDate>Wed, 28 Aug 2024 13:09:29 GMT</pubDate>
            <atom:updated>2026-01-10T19:59:50.081Z</atom:updated>
            <content:encoded><![CDATA[<h3>Keycloak Angular integration : Securing Angular application step-by-step guide</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/1*3G2L-6m48izk0gttL6Q2bA.png" /><figcaption>Keycloak with Angular</figcaption></figure><h3>Use case / Problem scenario</h3><p>Let’s say, we have an Angular application that we want to secure so that some of the pages can be accessed by authenticated users and rest of the page is open for all.</p><h3>What is a keycloak ?</h3><p>Keycloak is an open-source <strong>identity and access management (IAM)</strong> solution developed by <strong>Red Hat</strong>. It provides features for managing user identities and securing applications and services. Essentially, it helps organizations handle authentication and authorization in a centralized and streamlined manner.</p><p>Here are some key features of Keycloak:</p><p>1. <strong>Single Sign-On (SSO):</strong> Keycloak enables users to log in once and gain access to multiple applications without needing to log in again for each one.</p><p>2. <strong>Identity Federation: </strong>It allows integration with external identity providers, such as social login providers (e.g., Google, Facebook) and corporate directories (e.g., LDAP, Active Directory).</p><p>3. <strong>User Management:</strong> Administrators can manage user accounts, roles, and permissions from a centralized console.</p><p>4. <strong>Access Control:</strong> It supports role-based access control (RBAC) and fine-grained authorization policies.</p><p>5. <strong>Social Login Integration:</strong> Keycloak makes it easy to integrate with various social media platforms for authentication.</p><p>6. <strong>Two-Factor Authentication (2FA): </strong>It supports multiple forms of authentication to enhance security.</p><p>7. <strong>Customizable Authentication Flows:</strong> It allows you to create custom authentication processes to fit your specific needs.</p><p>8. <strong>OAuth 2.0 and OpenID Connect:</strong> Keycloak supports these popular protocols for secure API access and user authentication.</p><p>Overall, Keycloak is used to simplify and secure the management of user identities and permissions across various systems and applications.</p><h3>Keycloak Integration Benefits</h3><ul><li><strong>Single Sign-On (SSO):</strong> Users log in once to access multiple apps.</li><li><strong>Centralized User Management:</strong> Simplifies handling user accounts and permissions.</li><li><strong>Flexible Authentication Protocols:</strong> Supports OAuth 2.0, OpenID Connect, and SAML.</li><li><strong>Role-Based Access Control:</strong> Easily manage user roles and permissions.</li><li><strong>Social Login Integration:</strong> Supports login via social media accounts.</li><li><strong>Two-Factor Authentication (2FA):</strong> Enhances security with additional verification.</li><li><strong>Customizable Flows:</strong> Tailor authentication processes to fit your needs.</li><li><strong>Easy Angular Integration:</strong> Provides an Angular adapter for smooth setup.</li></ul><h3>Installing keycloak</h3><p>Keycloak can be installed in various ways, including using a Docker image, a standalone server, or a Helm chart. For our purposes, we’ll be using the standalone server option. For more details, visit <a href="https://www.keycloak.org/downloads">Keycloak Downloads</a>.</p><p>1. Run this docker command :</p><pre>docker run -p 8888:8080 -e KEYCLOAK_ADMIN=admin -e KEYCLOAK_ADMIN_PASSWORD=admin quay.io/keycloak/keycloak:24.0.1 start-dev</pre><p>This will start a Keycloak docker container with Admin account username:admin password:admin</p><p>2. Or another way:</p><p>create a <strong><em>docker-compose.yml</em></strong><em> </em>file as below:</p><pre>services:<br>    postgres:<br>        image: postgres:14<br>        container_name: keycloak-postgres<br>        environment:<br>            POSTGRES_DB: keycloak<br>            POSTGRES_USER: keycloak<br>            POSTGRES_PASSWORD: keycloak<br>        volumes:<br>            - postgres_data:/var/lib/postgresql/data<br>        networks:<br>            - keycloak-network<br>    keycloak:<br>        image: quay.io/keycloak/keycloak:24.0.1<br>        container_name: keycloak<br>        ports:<br>            - &#39;8888:8080&#39;<br>        environment:<br>            KEYCLOAK_ADMIN: admin<br>            KEYCLOAK_ADMIN_PASSWORD: admin<br>            DB_VENDOR: POSTGRES<br>            DB_ADDR: postgres<br>            DB_PORT: 5432<br>            DB_DATABASE: keycloak<br>            DB_USER: keycloak<br>            DB_PASSWORD: keycloak<br>        depends_on:<br>            - postgres<br>        networks:<br>            - keycloak-network<br>        command: [&#39;start-dev&#39;]<br><br>volumes:<br>    postgres_data:<br><br>networks:<br>    keycloak-network:</pre><p>This will start a Keyclaok docker container with a persistence state with a postgres database. Benefit of this, when we will shut down Keycloak container, we will not lose our configurations.</p><h3>Configuring Keycloak</h3><h4>Create a realm</h4><p>A realm in Keycloak functions as a tenant, representing a separate and isolated group of applications and users.</p><ul><li>Access the admin console at <strong>http://localhost:8888/auth/admin/</strong> and log in.</li><li>Click on the <strong>“Master”</strong> dropdown or the current realm name at the top left.</li><li>Select <strong>“Add realm”</strong></li><li>Provide a unique <strong>Realm Name</strong>. example: <strong><em>Tutorial-web</em></strong></li><li>Optionally, add a <strong>Display Name</strong>.</li><li>Click <strong>“Create”</strong> to add the new realm.</li><li>Adjust realm settings, including login, security, and client management.</li></ul><h4>Create a client</h4><ul><li>Click on <strong>“Clients”</strong> in the left menu.</li><li>Click <strong>“Create Client”</strong>.</li><li>Select <strong>Client type </strong>to <strong>“OpenID Connect”</strong></li><li>Enter a <strong>Client ID</strong>. example: <strong><em>angular-fe-client</em></strong></li><li>Enter name, description (optional), then press <strong>Next</strong></li><li>There are <strong>Client authentication, Authorization, Authorization </strong>settings<strong>. </strong>But let this as default settings for now, then press <strong>Next</strong></li><li>(Optional) Fill in <strong>Root URL</strong>. <strong>Home URL</strong></li><li>(Not Mandatory, but necessary) Fill in <strong>Valid redirect URIs (</strong><a href="http://localhost:4200/tutorials">http://localhost:4200/</a>*)</li><li>(Not Mandatory, but necessary) Fill in <strong>Web origins (</strong><a href="http://localhost:4200/tutorials">http://localhost:4200</a>)</li><li>(Not Mandatory, but necessary) Fill in <strong>Valid post logout redirect URIs (</strong><a href="http://localhost:4200/tutorials">http://localhost:4200</a>)</li><li><strong>Save Client:</strong> Click <strong>“Save”</strong>.</li></ul><h4>Create User</h4><ul><li><strong>Left menu:</strong> Click <strong>“Users”</strong>.</li><li><strong>Button:</strong> Click <strong>“Add user”</strong>.</li><li><strong>Fields:</strong> Enter <strong>Username</strong> (and optionally, <strong>Email</strong>, <strong>First Name</strong>).</li><li><strong>Button:</strong> Click <strong>“Save”</strong>.</li><li><strong>Tab:</strong> Go to <strong>“Credentials”</strong>.</li><li><strong>Fields:</strong> Enter and confirm <strong>Password</strong>.</li><li><strong>Button:</strong> Click <strong>“Set Password”</strong>.</li></ul><h3>Integrate keycloak with Angular</h3><p>I hope we already have an angular project running on our local environment that we want to secure with Keycloak.</p><p>I have one already. This is basic angular project build on following this tutorial here: <a href="https://www.bezkoder.com/angular-16-crud-example/">https://www.bezkoder.com/angular-16-crud-example/</a></p><p>I have updated some portions of it to make it ready for my next keycloak integration. The angular project can be found here:</p><p><a href="https://github.com/syedabdullahrahman/demo-project/tree/basic-angular-application">GitHub - syedabdullahrahman/demo-project at basic-angular-application</a></p><p>Before proceeding with the tutorial, the project can be cloned in a local environment or other angular project can be also used.</p><p>After creating the project, let’s install some dependencies:</p><pre>npm install keycloak-angular - save <br>npm install keycloak-js - save</pre><p>Next create an <strong><em>environment.ts</em></strong> file :</p><pre>export const environment = {<br>  production: false,<br>  keycloak: {<br>    enable: true, //Enable or disable Keycloak for Frontend app<br>    authority: &#39;http://localhost:8888&#39;, //Keycloak URL<br>    redirectUri: &#39;http://localhost:4200&#39;, //Frontend app URL<br>    postLogoutRedirectUri: &#39;http://localhost:4200/logout&#39;, //Optional value<br>    realm: &#39;Tutorial-web&#39;, //Realm name<br>    clientId: &#39;angular-fe-client&#39;,<br>  },<br>};</pre><p>Let’s update <strong><em>app.module.ts</em></strong> file:</p><pre>// required imports here ........<br><br>export const initializeKeycloak = (keycloak: KeycloakService) =&gt; async () =&gt; {<br>  if (environment.keycloak.enable) {<br>    /**<br>     *  https://www.npmjs.com/package/keycloak-angular#keycloak-js-events<br>     *  The callback events from keycloak-js are available through a RxJS subject which is defined by keycloakEvents$.<br>     *  For example you make keycloak-angular auto refreshing your access token when expired<br>     * <br>     **/<br>    keycloak.keycloakEvents$.subscribe({<br>      next(event) {<br>        if (event.type == KeycloakEventType.OnTokenExpired) {<br>          keycloak.updateToken(20);<br>        }<br>      },<br>    });<br>    return keycloak.init({<br>      config: {<br>        url: environment.keycloak.authority,<br>        realm: environment.keycloak.realm,<br>        clientId: environment.keycloak.clientId,<br>      },<br>      // If set a false you cannot get any information about the user example the username<br>      // if you use keycloakService.getUserName() you get this error<br>      // User not logged in or user profile was not loaded.<br>      loadUserProfileAtStartUp: true,<br>      initOptions: {<br>        //   This is an action we specified on keycloak load<br>        //   We have two options : &#39;login-required&#39;|&#39;check-sso&#39;<br>        //   If is set to &#39;login-required&#39; this means your browser will do a full redirect to the Keycloak server and back to your application.<br><br>        // onLoad: &#39;login-required&#39;,<br>        // checkLoginIframe: true,<br><br>        //   If is set to  &#39;check-sso&#39;  instead this action will be performed in a hidden iframe, so your application resources only need to be loaded and parsed once by the browser.<br>        //   Then you will need to add the silentCheckSsoRedirectUri and create a html file   silent-check-sso.html with this content<br>        // &lt;html&gt;<br>        //    &lt;body&gt;<br>        //         &lt;script&gt;<br>        //           parent.postMessage(location.href, location.origin);<br>        //         &lt;/script&gt;<br>        //      &lt;/body&gt;<br>        // &lt;/html&gt;<br>        onLoad: &#39;check-sso&#39;,<br>        silentCheckSsoRedirectUri:<br>          window.location.origin + &#39;/assets/silent-check-sso.html&#39;,<br>        checkLoginIframe: false,<br>        redirectUri: environment.keycloak.redirectUri,<br>      },<br>      // By default the keycloak-angular library add Authorization: Bearer TOKEN to all http requests<br>      // Then to exclude a list of URLs that should not have the authorization header we need to provide  them here.<br>      bearerExcludedUrls: [&#39;/assets&#39;],<br>    });<br>  }<br>};<br><br><br>@NgModule({<br>  bootstrap: [AppComponent],<br>  declarations: [<br>    AppComponent,<br>    AddTutorialComponent,<br>    TutorialsListComponent,<br>    TutorialDetailsComponent,<br>    //or Other components as per requirement...<br>  ],<br>  imports: [<br>    BrowserModule,<br>    KeycloakAngularModule, <br>    //Import KeycloakAngularModule to be available to the project<br>    CommonModule,<br>    BrowserModule,<br>    AppRoutingModule,<br>    FormsModule,<br>  ],<br>  providers: [<br>    //Initialize keyclaok service provider<br>    {<br>      provide: APP_INITIALIZER,<br>      useFactory: initializeKeycloak,<br>      multi: true,<br>      deps: [KeycloakService],<br>    },<br>    { provide: APP_BASE_HREF, useValue: &#39;/&#39; },<br>    {<br>      provide: TutorialService,<br>      useClass: environment.production ? TutorialService : MockTutorialService,<br>    },<br>  ],<br>})<br>export class AppModule {}</pre><p>Let’s create <strong><em>auth-guard.ts</em></strong></p><pre>export const AuthGuard: CanActivateFn = (): boolean =&gt; {<br>    const authenticationService = inject(AuthenticationService);<br>    if (authenticationService.isLoggedIn()) {<br>      return true;<br>    }<br>    authenticationService.redirectToLoginPage();<br>    return false;<br>  };</pre><p>Let’s update <strong><em>app-routing.module.ts.</em></strong></p><p>We need to add <strong><em>AuthGuard </em></strong>to those pages which we want to protect or want to be accessed by authenticated users only. For example, here Tutorial list is accessible by all, and Adding Tutorials page can be accessed by Authenticated users only.</p><pre>// required imports here ........<br><br>export enum AppRoutes {<br>  Home = &#39;&#39;,<br>  Tutorials = &#39;tutorials&#39;,<br>  TutorialsDetails = &#39;tutorials/:id&#39;,<br>  AddTutorials = &#39;add&#39;,<br>  Logout = &#39;logout&#39;,<br>  NotFound = &#39;404&#39;,<br>  AnyOther = &#39;**&#39;,<br>}<br><br>const routes: Routes = [<br>  { path: AppRoutes.Home, redirectTo: AppRoutes.Tutorials, pathMatch: &#39;full&#39; },<br>  { path: AppRoutes.Tutorials, component: TutorialsListComponent },<br>  { path: AppRoutes.TutorialsDetails, component: TutorialDetailsComponent },<br>  { path: AppRoutes.AddTutorials, canActivate: [AuthGuard], component: AddTutorialComponent },<br>  {<br>    path: AppRoutes.Logout,<br>    canActivate: [LogoutRouteGuard],<br>    component: LogoutScreenComponent,<br>  },<br>  {<br>    path: AppRoutes.AnyOther,<br>    redirectTo: AppRoutes.NotFound,<br>  },<br>  {<br>    path: AppRoutes.NotFound,<br>    component: NotFoundComponent,<br>  },<br>];<br><br>@NgModule({<br>  imports: [RouterModule.forRoot(routes)],<br>  exports: [RouterModule],<br>})<br>export class AppRoutingModule { }</pre><p>Let’s update <strong><em>app.component.ts</em></strong></p><pre>import { Component, OnInit } from &#39;@angular/core&#39;;<br><br>import { AuthenticationService } from &#39;./services/authentication.service&#39;;<br><br>@Component({<br>  selector: &#39;app-root&#39;,<br>  templateUrl: &#39;./app.component.html&#39;,<br>  styleUrls: [&#39;./app.component.css&#39;],<br>})<br>export class AppComponent implements OnInit {<br>  title = &#39;demo-angular-project&#39;;<br><br>  constructor(private authService: AuthenticationService) {}<br><br>  ngOnInit() {}<br><br>  isLoggedIn() {<br>    return this.authService.isLoggedIn();<br>  }<br><br>  username() {<br>    return this.authService.userName;<br>  }<br><br>  logout() {<br>    this.authService.logout();<br>  }<br><br>  login() {<br>    this.authService.redirectToLoginPage();<br>  }<br>}</pre><p>Let’s update<strong> <em>app.component.html</em></strong></p><p>It has two pages Tutorials page to show a list and Add page to add a tutorial. Basically, a CRUD screen. And at the left side login button and after login, just username and a logout button will be visible.</p><pre>&lt;div&gt;<br>    &lt;nav class=&quot;navbar navbar-expand-lg navbar navbar-dark bg-primary&quot;&gt;<br>      &lt;div class=&quot;container-fluid&quot;&gt;<br>      &lt;a class=&quot;navbar-brand text-light&quot; href=&quot;#&quot;&gt;Tutorials Hub&lt;/a&gt;<br>      &lt;button<br>        class=&quot;navbar-toggler&quot;<br>        type=&quot;button&quot;<br>        data-bs-toggle=&quot;collapse&quot;<br>        data-bs-target=&quot;#navbarNav&quot;<br>        aria-controls=&quot;navbarNav&quot;<br>        aria-expanded=&quot;false&quot;<br>        aria-label=&quot;Toggle navigation&quot;<br>      &gt;<br>          &lt;span class=&quot;navbar-toggler-icon&quot;&gt;&lt;/span&gt;<br>        &lt;/button&gt;<br>      &lt;div class=&quot;collapse navbar-collapse justify-content-between&quot; id=&quot;navbarNav&quot;&gt;<br>        &lt;div class=&quot;d-flex flex-row&quot;&gt;<br>          &lt;ul class=&quot;navbar-nav&quot;&gt;<br>            &lt;li class=&quot;nav-item&quot;&gt;<br>              &lt;a routerLink=&quot;tutorials&quot; class=&quot;nav-link text-light&quot;<br>                &gt;Tutorials&lt;/a<br>              &gt;<br>            &lt;/li&gt;<br>            &lt;li class=&quot;nav-item&quot;&gt;<br>              &lt;a routerLink=&quot;add&quot; class=&quot;nav-link text-light&quot;&gt;Add&lt;/a&gt;<br>            &lt;/li&gt;<br>          &lt;/ul&gt;<br>        &lt;/div&gt;<br><br>        &lt;div class=&quot;d-flex flex-row-reverse&quot;&gt;<br>          &lt;ul class=&quot;navbar-nav ms-auto mb-2 mb-lg-0&quot;&gt;<br>            &lt;ng-container *ngIf=&quot;isLoggedIn(); else loginLink&quot;&gt;<br>              &lt;li class=&quot;nav-item&quot;&gt;<br>                &lt;span class=&quot;nav-link text-light&quot;&gt;Hi {{ username() }} !&lt;/span&gt;<br>              &lt;/li&gt;<br>              &lt;li class=&quot;nav-item&quot;&gt;<br>                &lt;button class=&quot;btn btn-outline-light&quot; (click)=&quot;logout()&quot;&gt;<br>                  Logout<br>                &lt;/button&gt;<br>              &lt;/li&gt;<br>            &lt;/ng-container&gt;<br>            &lt;ng-template #loginLink&gt;<br>              &lt;li class=&quot;nav-item&quot;&gt;<br>                &lt;button class=&quot;btn btn-outline-light&quot; (click)=&quot;login()&quot;&gt;<br>                  Login<br>                &lt;/button&gt;<br>              &lt;/li&gt;<br>            &lt;/ng-template&gt;<br>          &lt;/ul&gt;<br>          &lt;/div&gt;<br>        &lt;/div&gt;<br>      &lt;/div&gt;<br>    &lt;/nav&gt;<br>    &lt;div class=&quot;container mt-3&quot;&gt;<br>      &lt;router-outlet&gt;&lt;/router-outlet&gt;<br>    &lt;/div&gt;<br>  &lt;/div&gt;</pre><p>That’s mostly done. So, our project has Keycloak added, we guarded some pages and buttons so that only authenticated users can see it.</p><p>For example,</p><ul><li>Tutorial list is visible to all.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*EGWjngL7etXPAn7bJX2RYQ.png" /></figure><ul><li>when we try to Add a tutorial, we will be redirected to Keyclaok for login.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*P-DgjooBMPDUxkT_yy89AA.png" /></figure><ul><li>similarly, when unauthenticated user can’t update the tutorial page.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*hEKq2HYB-AwLJgFNXlMD8A.png" /></figure><ul><li>only authenticated users can update the tutorial.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*YfLu5zg9Skgdi-U-8zKWDA.png" /></figure><p>That’s it for today.</p><p>I hope you’ve enjoyed it and learnt something new.</p><p>Please let me know in the comments what do you think.</p><p>The entire code for this project can be found in my GitHub repository:</p><p><a href="https://github.com/syedabdullahrahman/demo-project/tree/keycloak-angular-integration">GitHub - syedabdullahrahman/demo-project at keycloak-angular-integration</a></p><h3><strong>Upcoming next:</strong></h3><ul><li>Replacing the current Angular app <strong>mock-api </strong>code with Spring boot REST api</li><li>Secure the Spring boot REST api with Keyclaok</li><li>Generate <strong>open-api</strong> spec and use OpenAPI Generator to generate client code from Spring Boot REST api</li><li>Use <strong>open-api </strong>in Angular app</li><li>Update Keyclaok theme to look like custom organization etc……..</li></ul><p>Till then,</p><h3>Happy Coding !!!</h3><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=bd185333a304" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>