<?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[theoptimaltechnologist - Medium]]></title>
        <description><![CDATA[Subscribe to this publication to get a good idea on technologies that IT developers deal with, production strategies and various challenges they face. - Medium]]></description>
        <link>https://medium.com/theoptimaltechnologist?source=rss----3f040705275c---4</link>
        <image>
            <url>https://cdn-images-1.medium.com/proxy/1*TGH72Nnw24QL3iV9IOm4VA.png</url>
            <title>theoptimaltechnologist - Medium</title>
            <link>https://medium.com/theoptimaltechnologist?source=rss----3f040705275c---4</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Thu, 19 Nov 2026 19:56:19 GMT</lastBuildDate>
        <atom:link href="https://medium.com/feed/theoptimaltechnologist" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[What is Keycloak? How to use it — an example with nodejs? (Part 1)]]></title>
            <link>https://medium.com/theoptimaltechnologist/what-is-keycloak-how-to-use-it-an-example-with-nodejs-part-1-25434e963fed?source=rss----3f040705275c---4</link>
            <guid isPermaLink="false">https://medium.com/p/25434e963fed</guid>
            <category><![CDATA[expressjs]]></category>
            <category><![CDATA[nodejs]]></category>
            <category><![CDATA[tutorial]]></category>
            <category><![CDATA[keycloak]]></category>
            <category><![CDATA[security]]></category>
            <dc:creator><![CDATA[Nirabhra Tapaswi]]></dc:creator>
            <pubDate>Sun, 13 Sep 2020 20:06:07 GMT</pubDate>
            <atom:updated>2020-09-14T14:43:01.301Z</atom:updated>
            <content:encoded><![CDATA[<h3>What is Keycloak? How to use it — an example with nodejs? (Part 1)</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/280/1*vnXae8d0IpVQ6Loau5ksaA.png" /><figcaption><a href="https://www.keycloak.org/">Keycloak</a></figcaption></figure><p>As our world evolves towards getting more and more digital, our digital identities become more and more important, and with it, the means to verify them accurately.</p><p>What this means for software products is that they have to manage user identification and</p><p>access securely and concretely. But this isn’t easy right? I mean, as a business product manager, you would want to focus more on feature development and intrinsic value addition rather than solving already solved problems, as a friend once told me. I didn’t quite agree then, but eventually you should recognize the work done by others and welcome their ideas and work rather than always building everything from scratch.</p><p>On a similar note, I would say that building a native Identity Management and Access Control solution may seem intriguing, but if you have other important areas to work on, leave this to the pros — Keycloak.</p><p><strong>Keycloak</strong> is an Identity and Access Management(IAM) Software, which will act as an essential tool in your business product. IAM typically aims to verify the identity of a user or system which is requesting access to your environment, and evaluates a set of rules which tells what features and assets is that user/system has access to. The identity management and access management are two different entities. In classical situations, access management relies on an Identity Provider to verify the user, and builds on top of it to map the identity of the user/system with what it can do in an environment. Typically Role Based Access Control(RBAC) is a standard concept that is followed to establish an access control layer. A support layer is added to make use of this access management, basically a set of protocols to use this with other applications. Usually the protocol ends up being OAuth, which is a standard responsible for managing the access control parameters on the Authorization software side, as well as lay the guidelines to be followed by the applications utilizing the Authorization service.</p><p>If you wish to know more about IAM, you can refer to the following article, or other articles online:</p><p><a href="https://www.csoonline.com/article/2120384/what-is-iam-identity-and-access-management-explained.html">What is IAM? Identity and access management explained</a></p><p>I will move on to explain where Keycloak fits into the picture. Keycloak combines the power of a Identity Provider and a Authorization Server to give a foolproof IAM solution to us. Also it has out of the box integrations with social logins sites, other identity providers, as well as federate external user databases like LDAP servers. Keycloak thus seems like a software that we would want to use to reduce our IAM overhead.</p><h4>Installation</h4><p>Before we delve into the using Keycloak, I should tell you how to set it up quickly. I will suggest a docker installation available in your local, and we can use the docker image for keycloak easily.</p><pre>$ docker run -p 8080:8080 -e KEYCLOAK_USER=admin -e KEYCLOAK_PASSWORD=admin quay.io/keycloak/keycloak:latest</pre><p><a href="https://www.keycloak.org/getting-started/getting-started-docker">Docker</a></p><p>There are other ways to set it up, visit <a href="https://www.keycloak.org/docs/latest/getting_started/index.html">Keycloak’s Getting Started Guide</a>.</p><p>After the server is up and running, you can open the browser at <a href="http://192.168.0.110:8080/auth/">http://127.0.0.1:8080/auth/</a> and click on Administration Console, which should redirect you to <a href="http://192.168.0.110:8080/auth/admin/master/console/">http://127.0.0.1:8080/auth/admin/master/console/</a>. Log in to the master console with username password that you provided above(admin, admin for me).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*VCq4kNW_ndIrrsCEfjNQgQ.png" /><figcaption>Master Login</figcaption></figure><p>After we login, we can see the following page —</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*X4KVVVhkk670OExxcd5oGg.png" /><figcaption>Master Console</figcaption></figure><p>Let me explain what a realm is before we proceed. Keycloak tells us to think of a realm as an equivalent of a tenant. This can also be thought of as a namespace(if you are familiar with networks).</p><h4>Realm Creation</h4><p>Hover on the Master(realm) in the top right and select Add Realm. Here we create our new realm which is dedicated to the product that we are building-</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*JgVvFF08DxqHsLCy-A0Jlw.png" /><figcaption>Create Realm</figcaption></figure><p>Click on the create button and you should see the realm’s home page —</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*zTd84KWUZQzLypUSPqXejA.png" /><figcaption>Realm Home</figcaption></figure><p>Let me explain the side menu bar’s configure section quickly.</p><ul><li>Settings is to tune the realm settings like token expiry, themes, cache etc.</li><li>Clients is an important tab, and is used to create clients which represent the applications that we build for our product.</li><li>Client scopes are common scopes that clients can use. Scopes are entities that help the clients(applications) in their decision to grant or deny access to it’s resources(assets).</li><li>Roles are common set of classification which help majorly in granting access to certain applications’ assets. These can be used commonly across all the clients.</li><li>Identity Providers leverages the ability of external identity management systems to authenticate.</li><li>User Federation is to integrate Keycloak’s identity database with external User Databases like ldap servers.</li><li>Authentication is to control Keycloak’s default authentication/ authorization behavior. For most of the cases you won’t need to tweak this, as it is a slightly advanced feature for real fine tuning purposes.</li></ul><p>The manage section is fairly intuitive, where you can create and manage users, groups and sessions; and do imports and exports of settings. Events tab is to check the admin and user logs(like logins, changes etc) and add plugins that you write for Keycloak.</p><h4>Sample Application with Nodejs</h4><blockquote><strong><em>Keycloak configuration</em></strong></blockquote><p>Now that we are ready with our basic Keycloak console, let us build a basic application to feel this whole thing in action. Before we start with our nodejs code, let us complete our Keycloak setup.</p><p>First, let us create 2 roles, user and admin. Select the roles tab, and click on add role button —</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ewK6WzigWZgBQekw_IyHIw.png" /><figcaption>Role Create</figcaption></figure><p>Create admin in the same way(name it “admin” exactly for the purpose of this tutorial).</p><p>Now let us create an user. Go to users tab and click on add user button —</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6gQuPE4v9gUQm3F7yGMPzw.png" /><figcaption>User create</figcaption></figure><p>Now we set his password(credentials), by clicking on the credentials tab —</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*zp10MmRuLDo07hAJTiTJKQ.png" /><figcaption>User Credential</figcaption></figure><p>We now move on to assigning a role to our user, click on Role Mappings tab —</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*VLawSQJhpG6bN0vfnFGL6g.png" /><figcaption>User Add Role</figcaption></figure><p>Note that the roles we had earlier created is displayed here. Click on add selected to actually add the highlighted role(don’t add the admin role, we will want to see a denial of service due to the lack of this role for this user).</p><p>Now that we are ready with our user and have assigned him his role, lets move on to creating a client for our nodejs application(which we will code in a bit). Go to Clients tab and click on Create button —</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*f6ua7L6PcY8CJmpjLt1obw.png" /><figcaption>Client Create</figcaption></figure><p>Additionally, let us edit some properties of this client after its created —</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*jy3dMkYuTeIA_E2AekIF5g.png" /><figcaption>Client Edit</figcaption></figure><p>I would like to emphasize on the access type selection here. Notice that we changed the default(which is public) to confidential type. A brief overview of the types:-</p><ul><li><strong>Public client</strong>: When we cannot transmit client secrets over the channel to the application. For example in the case of browsers and mobile applications. Because each instance of a browser tab of mobile application is different and, and is almost always over public internet, we cannot pass a secret to them; and also there is a issue of trust, because the end user can have access to the secret if transmitted to his/her application(browser/ mobile etc).</li><li><strong>Bearer-only client</strong>: When we want our backend application to simple verify the token and get details on the scopes of the issued token, not have a fine grained access control on the particular application. Doesn’t have any resources(assets) associated to it.</li><li><strong>Confidential client</strong>: When we want a fine grained access control feature enabled by the keycloak server on the client application(running in the backend). Has resources(assets) associated to it.</li></ul><p>There are two important <em>distinguishing factors</em>, or say two categorizations between these 3 client types. First is <em>public clients</em> are used for user-end devices and not servers whereas the other two are used more often for backend services(servers side applications). The other important categorization is the ability of <em>confidential clients</em> to <em>register resources</em> on which it can perform <em>fine grained access control</em> using scopes, policies and permissions(its a really very powerful feature); this feature is not available for public and bearer-only clients.</p><p>Now that we understand these types, we will resume creation of our client with confidential type, and authorization enabled(service account is auto enabled with this). Enabling authorization actually enables us to define and use the fine grained access control that I mentioned. Save the client configuration, and you will see Authorization tab enabled at the top. Click on it, you will see the following —</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*NUacy8jLT60AlNzvstOk_g.png" /><figcaption>Authorization Home</figcaption></figure><p>Let me explain the function of each of the sub top navigation tabs of Authorization before me move ahead —</p><ul><li><strong>Resources</strong>: Manage resources, i.e. assets, of the application. This is the abstraction of the actual assets that the application(whose client this is) consists.</li><li><strong>Authorization Scopes</strong>: These are resource specific scopes that we can define to become part of our access control. This differs from the common Client Scopes which we saw earlier in the sense that these scopes hold meaning only in the context of this particular application’s resources, and not others. For example if we have 2 clients: client-1 with resource-1 and client-2 with resource-2; a scope say “read” would hold different meaning in the case of resource-1 and resource-2, based on how that application is actually written.</li><li><strong>Policies</strong>: These are the actual conditions that must be satisfied to return a permit object.</li><li><strong>Permissions</strong>: These bind policies to whole resources or specific scopes, to represent a wholesome permit/deny evaluation. This means that it links a policy(<em>which is essentially a boolean logic</em>) to an asset(or a part of it), providing the ultimate fine grained control that we spoke about.</li></ul><p>Now that we have a brief understanding of what Authorization is all about, let us create a authorization configuration for the application that we are building. Click on Authorization Scopes and then click create —</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*AF8nvk24BDWekNz2f71Jug.png" /><figcaption>Authorization Scope Create</figcaption></figure><p>Similarly create a write scope(ensure it’s name is exactly “write” for the sake of our tutorial). Now click on Resources tab and click on create —</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*KhnasQO42o81W_pE5P6xyQ.png" /><figcaption>Resource Create</figcaption></figure><p>Notice that we are associating read and write scope to this resource. Now click on Policies, click on Create Policy and select Role in the dropdown —</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ZagFOxSVkcr_EUPOrriSjQ.png" /><figcaption>Policy Create(Read)</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*GDAY_p8Iv_ADZyKmJosQQA.png" /><figcaption>Policy Create(Write)</figcaption></figure><p>Notice that we are associating different realm roles to these policies, defining our logic of grant evaluation.</p><p>Lastly, lets link these Resources, scopes and policies together! Click on Permissions tab and click on Create Permission and select Scope-Based from the dropdown —</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Kxq5OxZVg844cBsf4cdk_A.png" /><figcaption>Permission Create(Read)</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*VJbwNAbCf_valWMhf5ki3Q.png" /><figcaption>Permission Create(Write)</figcaption></figure><p>Notice how we bind a resource, its scope and the desired policy to create a permission, which becomes our evaluation logic for granting access.</p><p>Before we finish, let us test the configuration we made so far. Yes it can be done via the UI! Isn’t it great? Click on Evaulate tab, selecting the client, user and resource, scope and then clicking evaluate results in —</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*d2FWsPcU7C7cEH3AucG8iA.png" /><figcaption>Evaulate(Permit Example)</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*TyhIBqCXV5a2zDjbPezEmw.png" /><figcaption>Evaulate(Permit Result)</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*K7_Re80iox3qwD_bhBiO_w.png" /><figcaption>Evaulate(Deny Example)</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*f39ldAQBGyytunLCaSxycg.png" /><figcaption>Evaulate(Deny Result)</figcaption></figure><p>We have reached the end of this article, and to continue with our tutorial of building our nodejs application, I will continue onto the next article of this series(Part 2). Thankyou for reading this far, hold on a bit longer to see all this hard work and concepts crunching bear fruits.</p><p>Continue reading Part 2 —</p><p><a href="https://medium.com/theoptimaltechnologist/what-is-keycloak-how-to-use-it-an-example-with-nodejs-part-2-46b562e2b46c">What is Keycloak? How to use it — an example with nodejs? (Part 2)</a></p><p>Read more on the how to use Keycloak in a production environment with multiple microservices here (from the author of this series) —</p><p><a href="https://medium.com/@nirabhratapaswi/keycloak-for-securing-enterprise-applications-an-overview-fa99e5d0ab93">Keycloak for securing enterprise applications — an overview</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=25434e963fed" width="1" height="1" alt=""><hr><p><a href="https://medium.com/theoptimaltechnologist/what-is-keycloak-how-to-use-it-an-example-with-nodejs-part-1-25434e963fed">What is Keycloak? How to use it — an example with nodejs? (Part 1)</a> was originally published in <a href="https://medium.com/theoptimaltechnologist">theoptimaltechnologist</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[What is Keycloak? How to use it — an example with nodejs? (Part 2)]]></title>
            <link>https://medium.com/theoptimaltechnologist/what-is-keycloak-how-to-use-it-an-example-with-nodejs-part-2-46b562e2b46c?source=rss----3f040705275c---4</link>
            <guid isPermaLink="false">https://medium.com/p/46b562e2b46c</guid>
            <category><![CDATA[nodejs]]></category>
            <category><![CDATA[keycloak]]></category>
            <category><![CDATA[security]]></category>
            <category><![CDATA[tutorial]]></category>
            <category><![CDATA[expressjs]]></category>
            <dc:creator><![CDATA[Nirabhra Tapaswi]]></dc:creator>
            <pubDate>Sun, 13 Sep 2020 20:02:49 GMT</pubDate>
            <atom:updated>2020-09-14T11:38:30.514Z</atom:updated>
            <content:encoded><![CDATA[<h3><strong>What is Keycloak? How to use it — an example with nodejs? (Part 2)</strong></h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Jw9V__6jYhm2amP74D_0lw.png" /></figure><p>Welcome back to our two part series on configuring and using <strong>Keycloak</strong> in real world. In this part I will focus more on using the Keycloak setup that we configured back in Part 1 in a <strong>nodejs express</strong> application.</p><p>Now, I have been with javascript for a long time, since I was introduced to web development, which is the reason I found it easy to integrate with a nodejs application. On the other side, there are lots of easy to use Java adapters(framework specific) that you will find <a href="https://www.keycloak.org/docs/latest/securing_apps/#openid-connect-3">here </a>—</p><p><a href="https://www.keycloak.org/docs/latest/securing_apps/#openid-connect-3">Securing Applications and Services Guide</a></p><p>And for other programming languages, there are unofficial libraries that provide easy integration with basic Keycloak features, but I would recommend using <a href="https://www.keycloak.org/docs/latest/securing_apps/#_keycloak_generic_adapter">Keycloak Gatekeeper</a> —</p><p><a href="https://www.keycloak.org/docs/latest/securing_apps/#_keycloak_generic_adapter">Securing Applications and Services Guide</a></p><p>Also, its fairly easy to implement the apis of Keycloak and develop a custom keycloak service in any programming language. I shall create a api tutorial later for ease of integration with other programming languages or bash via http(s) protocol. Just remember, with increasing proficiency in programming languages and technology concepts, your dependency on external libraries decreases as you understand implementation specifics better. Not that using libraries are bad(as I mentioned before, don’t reinvent unless necessary), but if the 3rd party libraries with unreliable maintainers, better rewrite it so that improvements on it become easy.</p><p>Okay, enough talk, lets start building our nodejs express application. First of all, you will need nodejs and npm installed in your system. Firstly, create a folder to work on, and run a few getting ready commands —</p><pre>$ mkdir keycloak-express<br>$ cd keycloak-express<br>$ npm init<br>$ npm install express ejs express-session keycloak-connect serve-favicon --save</pre><p>The directory structure will finally look like —</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/412/1*4e0A4Bo2lv6pvF2lJRgTKA.png" /><figcaption>directory structure</figcaption></figure><p>We will get to know all of these during the tutorial, lets begin with index.js. It is the entry-point to our expressjs server. We will be using ejs(embedded javascript) format for html embedded javascript coding(ejs its an old pattern but its quite easy to use and feels just like javascript).</p><p>Lets begin with writing the basic express server code —</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/72a09ba7f2439dfc117aeae51faca686/href">https://medium.com/media/72a09ba7f2439dfc117aeae51faca686/href</a></iframe><p>I won’t be explaining in depth the express framework or how nodejs http server works, that is out out of the scope of this article, but only some logical parts of the code which is necessary for understanding. Observe that we have two GET routes at paths “/” and “/home” respectively. Our ultimate goal will be to show an authenticated user the home page with his name and some details on this screen. Lets look at the initial version of our home.ejs(think of it like html only, with abilities to include javascript within it). This is how home.ejs should look like —</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/8da5f022430b7ade540a1708172ea673/href">https://medium.com/media/8da5f022430b7ade540a1708172ea673/href</a></iframe><p>In the home.ejs file, we are simply checking for the presence of a user object, and in case it is absent, we want the user to login. We have not yet included the login logic yet. You can run the server at this point —</p><pre># node index.js</pre><p>Visit <a href="http://127.0.0.1:3000/home">http://127.0.0.1:3000/home</a> to see the name ‘John’ being printed.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xOca7LLFhkKdfeAqMQxLrw.png" /><figcaption>Browser</figcaption></figure><p>Well, that is not impressive.. But have a bit of patience, we will get to the awesome parts. Before we proceed, let us get the client adapter configuration file from Keycloak. Go to the client(my-product), click on Installation tab and select <strong>Keycloak OIDC JSON</strong> option.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ldwgc59I3z-gatiNtML0dA.png" /><figcaption>keycloak.json</figcaption></figure><p>Save this as keycloak.json adjacent to our index.js server file(refer directory structure).</p><p>Before we proceed to introduce keycloak code for our express app, I would like to briefly tell you about the tokens that Keycloak returns when logging in a user —</p><ul><li><strong>Access Token</strong>: Contains claims about the user and it’s roles, permissions, groups etc. This is the actual token which is evaluated for granting access to protected resources.</li><li><strong>Refresh Token</strong>: Think of it as a session token(Keycloak does). This token is responsible to issuing new access tokens(which are short lived by convention) till this itself expires, which will lead to a re-login scenario.</li><li><strong>ID Token</strong>: This is a token containing claims about the user’s details. By default it has the same amount of user’s details claims as the access token, but as new user details are added, ID Token is supposed to have them by convention.</li></ul><p>Lets edit our index.js file to include keycloak login and authentication functions —</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e67779f9fc6eb4e68514534b5aefbc02/href">https://medium.com/media/e67779f9fc6eb4e68514534b5aefbc02/href</a></iframe><p>Let us go over this file, firstly, we import keycloak-connect, which is our keycloak client adapter. Then we initialize a memory store(memoryStore), which is used by keycloak-connect for internal token caching. Finally, what we are interested is in the middlewares introduced in routes “/home” and “/login”. This route internally redirects the user to Keycloak’s <em>my-product</em> realm’s login page, with a redirect to the the actual url that we requested(in this case “http://127.0.0.1:3000/login” or “http://127.0.0.1:3000/home” whichever we called first. The keycloak.protect() function makes sure we have a valid token from Keycloak before we access the actual function backing that route. Note, here “/login” is just a formality for frontend convenience, as keycloak.protect() would redirect unauthenticated requests to any of “/login” or “/home” to “<em>my-product</em>” login page. Before we go ahead and change our home.ejs template, lets try this new piece of code out. Restart the server with ctrl + c and running ($ node index.js) again(explore nodemon or yarn tools for auto-restarting servers). Open <a href="http://127.0.0.1:3000/login">http://127.0.0.1:3000/login</a>, we immidiately get redirected to Keycloak’s “my-product” realm, enter credentials and see if the outputs match —</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2m_LUaH43vwKUeiFUU6BWg.png" /><figcaption>my-product login</figcaption></figure><blockquote>NOTE: My keycloak is hosted on a different server in my network, not my localhost hence the URL is what you see above, it should come 127.0.0.1/localhost for you if you have installed it in the same machine.</blockquote><p>Now, after this you would ideally expect to get logged in, and see the home.ejs page from earlier(because if you see index.js login route function, we see redirect to home on successful login). Lets see what we get —</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*z_H56295uue7Px09sBg99Q.png" /><figcaption>access denied</figcaption></figure><p>If you are quite new to Keycloak, by this time you will be confused. Don’t worry it is expected. Are you wondering where we went wrong? Maybe the nodejs code? Or some Keycloak configuration? Afterall we have gone through alot of setup, something may have gone wrong. But the real reason is a very useful security concept that Keycloak implements called audience checking. Refer to the following article for in-depth clarity —</p><p><a href="https://www.keycloak.org/docs/latest/server_admin/#_audience">Server Administration Guide</a></p><p>The overall idea is that the way clients verify tokens is configurable to include audience verification. This mitigates the possibility of unwanted access to applications even with correct roles(such as unintended server to server communication). The tokens will be evaulated to deny if the it does not have that particular client as an audience. In our case, we have to add a scope to our “my-application” client which adds itself as an intended audience when undergoing a login process. Read more about protocol-mappers, scopes and claims on the official <a href="https://www.keycloak.org/">Keycloak website</a> to understand these very important concepts in depth.</p><p>Navigate to the Client Scopes page in Keycloak, click on Create button and add a new client scope “my-application-scope” —</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*BThgmMeDkDgbScEXJj0CRw.png" /><figcaption>Client Scope Create</figcaption></figure><p>Then select Mappers from the tab bar, click on Create button, and create a mapper with name “my-application-audience-protocol-mapper” —</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*gmUy5xS5QItVM6skjYC1fQ.png" /><figcaption>Audience Protocol Mapper Create</figcaption></figure><p>In the above select Mapper Type Audience, so that Keycloak knows in which field of the encoded tokens to add the audience values. You can disable add to ID token switch if you want, I am just going to leave it as it is. Lastly go to Clients page, select “my-application”, click on Client Scopes, and add this newly added client scope to it —</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*iitG2oe5o3l8s8WhmMCLVQ.png" /><figcaption>Client Scopes Add</figcaption></figure><p>Now we are ready to test our nodejs code again. First hit “http://127.0.0.1:3000/logout” to clear the current session token with no audience parameters. Then go to “http://127.0.0.1:3000/login” again and login to Keycloak’s login page. Now you should see the following page after a successful login —</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*DF7Ie3Z5nvmN5LUWcAkUag.png" /><figcaption>audience verify success, login success</figcaption></figure><p>We have accomplished a major feat with Keycloak and nodejs. But we still have a few features to test out. We have logged in yes, and our routes are authentication protected, but what about authorization? Remember that we already have an authorization framework ready in our Keycloak(and we already tested it with Evaluate tab in Authorization under Client). Lets edit our code to look at how we can protect some routes to specifically demand permissions. Here is our final index.js —</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e44dcec01d6124d7a5d8ac365850a3c7/href">https://medium.com/media/e44dcec01d6124d7a5d8ac365850a3c7/href</a></iframe><p>We have added 2 additional routes(GET “/asset01”, GET “/asset01/update”) to showcase the authorization check feature of Keycloak. Ideally the second route, i.e. “asset01/update” should have been a POST request, but here we are using GET route because it simplifies our frontend request from UI. You can see in the <strong>keycloak.enforcer</strong> middleware funtion that the resource and scope are passed as a “:” concatenated string(a demand of the library, not keycloak itself). This ensures whatever function lies at the end of the route path is accessed by only users with the required scope access on the resource. In our case, our “/asset01” endpoint requires a <strong>read</strong> scope permission on <strong>asset-01</strong> resource, and “/asset01/update” endpoint requires a <strong>write</strong> scope permission on <strong>asset-01</strong> resource. If you remember, we had granted our user John Halpert a user role, which we saw in our permissions tab that is allowed to access only the <strong>read</strong> scope of asset-01 resource, not <strong>write</strong>. Also, I have modified the “/home” route slightly to take the name, email and username from the id token or the access token, with the help of a simple <em>parseToken</em> function which converts the base64 encoded jwt’s payload to a JSON parsed object(you can console.log the payload to introspect the token’s content). Lets modify home.ejs a bit to capture the new information we are sending —</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/0f89e77d0c1f3608c7d345252594bb08/href">https://medium.com/media/0f89e77d0c1f3608c7d345252594bb08/href</a></iframe><p>Lets see it in action, first logout(“http://127.0.0.1:3000/logout”), followed by a automated redirect to Keycloak’s login page, where you should log in. You should be redirected to “/home” on successful login, where you can see —</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ck-kYk3VoYqg_8ubPxV51Q.png" /><figcaption>home</figcaption></figure><p>Then we can go to the url “http://127.0.0.1:3000/asset01” and we should find a success response —</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*20dLmBYPQYhfNM9RH2KXMg.png" /><figcaption>asset01 read success</figcaption></figure><p>And the path “http://127.0.0.1:3000/asset01/update” should give an access denied —</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*P3b67HgxXurX0zAYziKKDg.png" /><figcaption>asset01 write access denied</figcaption></figure><p>So there we go, all done. We have successfully integrated a full fledged IAM software with our application. There are a lot of more things that Keycloak can do, so tweak it, study it, explore it in depth to secure you application the best way possible.</p><p>Thank you for staying this long, hope this series helped you.</p><p>Read Part 1 of this series —</p><p><a href="https://medium.com/theoptimaltechnologist/what-is-keycloak-how-to-use-it-an-example-with-nodejs-part-1-25434e963fed">What is Keycloak? How to use it — an example with nodejs? (Part 1)</a></p><p>Read more on the how to use Keycloak in a production environment with multiple microservices here —</p><p><a href="https://medium.com/@nirabhratapaswi/keycloak-for-securing-enterprise-applications-an-overview-fa99e5d0ab93">Keycloak for securing enterprise applications — an overview</a></p><p>Full Code of tutorial —</p><p><a href="https://github.com/nirabhratapaswi/keycloak-nodejs-tutorial">nirabhratapaswi/keycloak-nodejs-tutorial</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=46b562e2b46c" width="1" height="1" alt=""><hr><p><a href="https://medium.com/theoptimaltechnologist/what-is-keycloak-how-to-use-it-an-example-with-nodejs-part-2-46b562e2b46c">What is Keycloak? How to use it — an example with nodejs? (Part 2)</a> was originally published in <a href="https://medium.com/theoptimaltechnologist">theoptimaltechnologist</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>