<?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 Jawad Rashid on Medium]]></title>
        <description><![CDATA[Stories by Jawad Rashid on Medium]]></description>
        <link>https://medium.com/@jawadrashid?source=rss-c13478e3b633------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*yuI4KpoBlMCGksHc7LW2gg.jpeg</url>
            <title>Stories by Jawad Rashid on Medium</title>
            <link>https://medium.com/@jawadrashid?source=rss-c13478e3b633------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 29 Nov 2026 20:17:48 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@jawadrashid/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[Accessing Keycloak API using Java and AWS Lambda — Part 2]]></title>
            <link>https://medium.com/@jawadrashid/accessing-keycloak-api-using-java-and-aws-lambda-part-2-198e4e418707?source=rss-c13478e3b633------2</link>
            <guid isPermaLink="false">https://medium.com/p/198e4e418707</guid>
            <category><![CDATA[docker]]></category>
            <category><![CDATA[java]]></category>
            <category><![CDATA[java-app-development]]></category>
            <category><![CDATA[keycloak]]></category>
            <category><![CDATA[aws-lambda]]></category>
            <dc:creator><![CDATA[Jawad Rashid]]></dc:creator>
            <pubDate>Mon, 29 Jul 2024 14:59:31 GMT</pubDate>
            <atom:updated>2024-07-29T14:59:31.108Z</atom:updated>
            <content:encoded><![CDATA[<h3>Accessing Keycloak API using Java and AWS Lambda — Part 2</h3><h3>Introduction</h3><p>This is a continuation for Part 1 where I created docker with Keycloak with Node.JS lambda function. I will extend the previous tutorial here: <a href="https://medium.com/@jawadrashid/accessing-keycloak-api-using-node-js-and-aws-lambda-part-1-5782437afaf2">https://medium.com/@jawadrashid/accessing-keycloak-api-using-node-js-and-aws-lambda-part-1-5782437afaf2</a>. You can find the Keycloak Java documentation here: <a href="https://www.keycloak.org/docs-api/25.0.2/javadocs/">https://www.keycloak.org/docs-api/25.0.2/javadocs/</a></p><h3>Table of Contents</h3><ul><li><a href="#7f72">Introduction</a></li><li><a href="#3272">Docker Setup</a></li><li><a href="#8f2a">How to create Java app For AWS Lambda</a></li><li><a href="#b2d6">Our Java Lambda Function Code</a></li><li><a href="#a9e1">Compiling Java code</a></li><li><a href="#0da6">Deploying Java Changes to Docker</a></li><li><a href="#0cd9">Testing the Java Lambda Function Locally Docker</a></li><li><a href="#cb13">Deploying the AWS Lambda To Amazon AWS</a></li><li><a href="#34a0">Final Remarks</a></li><li><a href="#020a">Resources</a></li></ul><h3>Docker Setup</h3><p>The docker setup is similar to part 1 for Node.js with 2 services added for Java sessions applications. The updated docker-compose.yaml is below:</p><pre>services:<br>  keycloak_demo:<br>    image: quay.io/keycloak/keycloak:25.0.2<br>    command: start-dev<br>    environment:<br>      KC_DB: postgres<br>      KC_DB_URL_HOST: postgres_keycloak_demo<br>      KC_DB_URL_DATABASE: keycloak<br>      KC_DB_PASSWORD: password<br>      KC_DB_USERNAME: keycloak<br>      KC_DB_SCHEMA: public<br>      KEYCLOAK_ADMIN: admin<br>      KEYCLOAK_ADMIN_PASSWORD: admin<br>    ports:<br>      - &quot;8890:8080&quot;<br>    depends_on:<br>      postgres_keycloak_demo:<br>        condition: service_healthy<br>    networks:<br>      - keycloak_demo_dev_network<br><br>  postgres_keycloak_demo:<br>    image: postgres:16.3<br>    command: postgres -c &quot;max_connections=200&quot;<br>    volumes:<br>      - pgdata_keycloak_data:/var/lib/postgresql/data<br>    environment:<br>      POSTGRES_DB: keycloak<br>      POSTGRES_USER: keycloak<br>      POSTGRES_PASSWORD: password<br>    healthcheck:<br>      test: &quot;exit 0&quot;<br>    ports:<br>      - &quot;5436:5432&quot;<br>    networks:<br>      - keycloak_demo_dev_network<br><br>  lambda-node:<br>    build: ./lambda-node<br>    ports: <br>      - &quot;9000:8080&quot;<br>    depends_on:<br>      - keycloak_demo<br>    networks:<br>      - keycloak_demo_dev_network<br><br>  lambda-java-getsessions:<br>    build: ./lambda-java/getsessions<br>    ports: <br>      - &quot;9100:8080&quot;<br>    depends_on:<br>      - keycloak_demo<br>    networks:<br>      - keycloak_demo_dev_network<br><br>  lambda-java-terminatesessions:<br>    build: ./lambda-java/terminatesessions<br>    ports: <br>      - &quot;9200:8080&quot;<br>    depends_on:<br>      - keycloak_demo<br>    networks:<br>      - keycloak_demo_dev_network<br><br>      <br>volumes:<br>  pgdata_keycloak_data:<br>networks:<br>  keycloak_demo_dev_network:<br>    driver: bridge</pre><ul><li>Here I have added 2 services one for the getting services for java and one for terminate sessions.</li><li>There are two folders inside lambda-java folder. One is named <strong>getsessions </strong>which is for getting sessions java app and the other is <strong>terminatesssions </strong>app for terminating sessions.</li><li>The Dockerfile in each folder is same and given below. I will explain the code later on:</li></ul><pre>FROM public.ecr.aws/lambda/java:21<br><br># Copy function code and runtime dependencies from Maven layout<br>COPY target/classes ${LAMBDA_TASK_ROOT}<br>COPY target/dependency/* ${LAMBDA_TASK_ROOT}/lib/<br><br># Set the CMD to your handler (could also be done as a parameter override outside of the Dockerfile)<br>CMD [ &quot;com.keycloak.sessionsapp.App::handleRequest&quot; ]</pre><h3>How to create Java app For AWS Lambda</h3><p>The instructions on how to create Java app for AWS lambda is given here: <a href="https://docs.aws.amazon.com/lambda/latest/dg/java-image.html#java-image-instructions">https://docs.aws.amazon.com/lambda/latest/dg/java-image.html#java-image-instructions</a></p><ul><li>In prerequistes you will need Java (version 20 tutorial) installed on your computer, Docker, Apache Maven and AWS CLI.</li><li>Docker should already be installed. The instructions are given in previous tutorial but you can install by going to <a href="https://docs.aws.amazon.com/cli/latest/userguide/getting-started-install.html">https://docs.aws.amazon.com/cli/latest/userguide/getting-started-install.html</a></li><li>Apache Maven can be installed by maven official website.</li></ul><p>Next we will create a project for Java. <strong>(You don’t need to follow these steps if you are using my code but if you want to create your own then you should follow these steps)</strong></p><ol><li>Run linux or Powershell command to create a project. Replace groupid with your project group id, artifact id should be the name of final output and region to where you want to deploy:</li></ol><pre>mvn -B archetype:generate \<br>   -DarchetypeGroupId=software.amazon.awssdk \<br>   -DarchetypeArtifactId=archetype-lambda -Dservice=s3 -Dregion=US_WEST_2 \<br>   -DgroupId=com.example.myapp \<br>   -DartifactId=myapp</pre><pre>mvn -B archetype:generate `<br>   &quot;-DarchetypeGroupId=software.amazon.awssdk&quot; `<br>   &quot;-DarchetypeArtifactId=archetype-lambda&quot; &quot;-Dservice=s3&quot; &quot;-Dregion=US_WEST_2&quot; `<br>   &quot;-DgroupId=com.example.myapp&quot; `<br>   &quot;-DartifactId=myapp&quot;</pre><p>2. Go to your main source file <em>myapp</em>/src/main/java/com/example/<em>myapp</em> and open App.java. It contains sample code which just outputs the payload.</p><p>3. Create Dockerfile</p><pre>FROM public.ecr.aws/lambda/java:21<br>  <br># Copy function code and runtime dependencies from Maven layout<br>COPY target/classes ${LAMBDA_TASK_ROOT}<br>COPY target/dependency/* ${LAMBDA_TASK_ROOT}/lib/<br>    <br># Set the CMD to your handler (could also be done as a parameter override outside of the Dockerfile)<br>CMD [ &quot;com.example.myapp.App::handleRequest&quot; ]</pre><p>4. Compile</p><pre>mvn compile dependency:copy-dependencies -DincludeScope=runtime</pre><p>5. Build docker image</p><pre>docker build --platform linux/amd64 -t docker-image:test .</pre><p>6. To test run command:</p><pre>docker run --platform linux/amd64 -p 9000:8080 docker-image:test</pre><p>7. Test the code locally by running the following command with payload(You can call without payload if not needed):</p><pre>Invoke-WebRequest -Uri &quot;http://localhost:9000/2015-03-31/functions/function/invocations&quot; -Method Post -Body &#39;{&quot;payload&quot;:&quot;hello world!&quot;}&#39; -ContentType &quot;application/json&quot;</pre><p>8. You will get response with your payload output in json format as that is what the lambda function is currently doing.</p><p>9. You can deploy it to aws lambda service by following section <strong>Deploying the image </strong>on <a href="https://docs.aws.amazon.com/lambda/latest/dg/java-image.html#java-image-instructions">https://docs.aws.amazon.com/lambda/latest/dg/java-image.html#java-image-instructions</a></p><h3>Our Java Lambda Function Code</h3><ul><li>Following the guide in last section I created seperate applications for gettingsesssions and terminatingsessions</li><li>Dockerfile in each folder is below:</li></ul><pre>FROM public.ecr.aws/lambda/java:21<br><br># Copy function code and runtime dependencies from Maven layout<br>COPY target/classes ${LAMBDA_TASK_ROOT}<br>COPY target/dependency/* ${LAMBDA_TASK_ROOT}/lib/<br><br># Set the CMD to your handler (could also be done as a parameter override outside of the Dockerfile)<br>CMD [ &quot;com.keycloak.sessionsapp.App::handleRequest&quot; ]</pre><ul><li>Basically in the docker file we are using aws lambda java version 21. Then we are copying the classes and dependencies in correct place.</li><li>Finally we are calling our lambda function in container.</li></ul><p>In each pom.xml other than the standard generated dependencies we need to add keycloak admin client library by adding following dependency(the version should match your keycloak version)</p><pre>&lt;dependency&gt;<br>      &lt;groupId&gt;org.keycloak&lt;/groupId&gt;<br>      &lt;artifactId&gt;keycloak-admin-client&lt;/artifactId&gt;<br>      &lt;version&gt;25.0.2&lt;/version&gt;<br>  &lt;/dependency&gt;</pre><p>Before explaining the App.java functionality let me show the docker-compose file that is deploying both of the java apps.</p><pre>lambda-java-getsessions:<br>    build: ./lambda-java/getsessions<br>    ports: <br>      - &quot;9100:8080&quot;<br>    depends_on:<br>      - keycloak_demo<br>    networks:<br>      - keycloak_demo_dev_network<br><br>  lambda-java-terminatesessions:<br>    build: ./lambda-java/terminatesessions<br>    ports: <br>      - &quot;9200:8080&quot;<br>    depends_on:<br>      - keycloak_demo<br>    networks:<br>      - keycloak_demo_dev_network</pre><ul><li>Here we are creating seperate services at port <strong>9100 </strong>for getssisons and <strong>9200 </strong>for terminatesessions.</li><li>Also, we are building the docker file I gave above which copies the generated classes and deploys it in container.</li></ul><p><strong>getsessions Java App</strong></p><ul><li>App.java for getsessions is below. We will discuss this in more detail:</li></ul><pre>package com.keycloak.sessionsapp;<br><br>import java.util.ArrayList;<br>import java.util.LinkedHashMap;<br>import java.util.List;<br><br>import org.keycloak.OAuth2Constants;<br>import org.keycloak.admin.client.Keycloak;<br>import org.keycloak.admin.client.KeycloakBuilder;<br>import org.keycloak.representations.idm.UserRepresentation;<br>import org.keycloak.representations.idm.UserSessionRepresentation;<br><br>import com.amazonaws.services.lambda.runtime.Context;<br>import com.amazonaws.services.lambda.runtime.RequestHandler;<br><br>import software.amazon.awssdk.services.s3.S3AsyncClient;<br><br>/**<br> * Lambda function entry point. You can change to use other pojo type or implement<br> * a different RequestHandler.<br> *<br> * @see &lt;a href=https://docs.aws.amazon.com/lambda/latest/dg/java-handler.html&gt;Lambda Java Handler&lt;/a&gt; for more information<br> */<br>public class App implements RequestHandler&lt;Object, Object&gt; {<br>    private final S3AsyncClient s3Client;<br><br>    public App() {<br>        // Initialize the SDK client outside of the handler method so that it can be reused for subsequent invocations.<br>        // It is initialized when the class is loaded.<br>        s3Client = DependencyFactory.s3Client();<br>        // Consider invoking a simple api here to pre-warm up the application, eg: dynamodb#listTables<br>    }<br><br>    @Override<br>    public Object handleRequest(final Object input, final Context context) {<br>     String serverUrl = &quot;http://keycloak_demo:8080&quot;;<br>     String realmName = &quot;Demo&quot;;<br>     String mainAdminRealm = &quot;master&quot;;<br>     <br>     LinkedHashMap&lt;String, String&gt; inputHashMap = (LinkedHashMap&lt;String, String&gt;) input; <br>     String user = inputHashMap.get(&quot;username&quot;);<br>     if(inputHashMap.containsKey(&quot;realm&quot;)) {<br>      realmName = inputHashMap.get(&quot;realm&quot;);<br>     }<br>     <br>     Keycloak keycloak = KeycloakBuilder.builder() //<br>                .serverUrl(serverUrl) //<br>                .realm(mainAdminRealm) //<br>                .grantType(OAuth2Constants.CLIENT_CREDENTIALS) //<br>                .clientId(&quot;demo-client&quot;) //<br>                .clientSecret(&quot;CLIENT_SECRET_GOES_HERE&quot;) //<br>                .build();<br>     <br>     List&lt;UserRepresentation&gt; users = keycloak.realm(realmName)<br>            .users()<br>            .searchByUsername(user, true);<br>     <br>     <br>     <br>     <br>     if(users.size() == 0) {<br>      return &quot;No User Found&quot;;<br>     }<br>     <br>     UserRepresentation foundUser = users.get(0);<br><br>     List&lt;UserSessionRepresentation&gt; sessionsList = keycloak.realm(realmName).users().get(foundUser.getId()).getUserSessions();<br>     <br>     if(sessionsList.size() == 0) {<br>      return &quot;No User Session Found&quot;;<br>     }<br>     <br>     List &lt;String&gt; userSessions = new ArrayList&lt;String&gt;();<br>     for(UserSessionRepresentation session : sessionsList) {<br>      String format = String.format(&quot;Id: %s, Username: %s, UserId: %s, ipAddress: %s, Start: %d, LastAccess: %d&quot;, <br>        session.getId(), session.getUsername(), session.getUserId(), session.getIpAddress(), session.getStart(), session.getLastAccess());<br>      System.out.println(format);<br>      userSessions.add(format);<br>     }<br>     System.out.println(userSessions);<br>     <br>     <br>     <br>        return sessionsList;<br>    }<br>    <br>}</pre><p>You need to change the following settings:</p><p>In both App.java in src/main/com/keycloak/sessionsapp under getsessions and terminatesessions folder under lambda-java there are some changes that need to be made. (You will need to change 2 files both App.java in sessions folders)</p><ul><li>In handleRequest change serverUrl to your keycloak url.</li><li>Optionally you can change realmName to the realm you want to query but if you want you can give this realmName when invoking the AWS lambda function through terminal, aws command or Postman by setting <strong>realm</strong> value in body.</li><li>In lines <strong>46–52</strong> change clientId to your main master client id you created and client secret to your secret.</li></ul><p>Other than the above changes no other change is needed but you need to look at the next section on how to compile the code to create classes and lib files.</p><h3>Compiling Java code</h3><p>Go to the root of the folder i.e. lambda-java/getsessions or lambda-java/terminatesessions in terminal and run the following command(You need to have maven installed on your computer)</p><pre>mvn compile dependency:copy-dependencies -DincludeScope=runtime</pre><p>After this is successful you will need to follow the instructions for deploying on docker to run the code.</p><h3>Deploying Java Changes to Docker</h3><ul><li>If your docker containers for this project are not running then run the command below to build java code:</li></ul><pre>docker-compose down --remove-orphans<br>docker-compose up --build -d</pre><ul><li>If containers are running and you make changes in lambda-java folder src file then just run the following commands to recreate the lambda-java services:</li></ul><p>For getsessions:</p><pre>docker-compose stop lambda-java-getsessions<br>docker-compose up lambda-java-getsessions --build -d</pre><p>For terminatesessions</p><pre>docker-compose stop lambda-java-terminatesessions<br>docker-compose up lambda-java-terminatesessions --build -d</pre><h3>Testing the Java Lambda Function Locally Docker</h3><p><strong>For Powershell:</strong></p><p>Run the following command. Our server is running on localhost on port 9100 for getsessions and 9200 for terminatesessions. Important thing is the payload/body<strong> ‘{“username”: “user”, “realm”: “Demo”}’</strong>. Here username is the username of user we want to get sessions for and realm is the realm name where user exists. Here realm is optional. If not given it will use KEYCLOAK_REALM.</p><p>For getsessions:</p><pre>Invoke-WebRequest -Uri &quot;http://localhost:9100/2015-03-31/functions/function/invocations&quot; -Method Post -Body &#39;{&quot;username&quot;: &quot;user&quot;, &quot;realm&quot;: &quot;Demo&quot;}&#39; -ContentType &quot;application/json&quot;</pre><p>For terminatesessions</p><pre>Invoke-WebRequest -Uri &quot;http://localhost:9200/2015-03-31/functions/function/invocations&quot; -Method Post -Body &#39;{&quot;username&quot;: &quot;user&quot;, &quot;realm&quot;: &quot;Demo&quot;}&#39; -ContentType &quot;application/json&quot;</pre><p>Response will be like this:</p><pre>{&quot;statusCode&quot;:200,&quot;body&quot;:[{&quot;id&quot;:&quot;b1f61547-8860-4de0-9e3c-3c5f88afd650&quot;,&quot;username&quot;:&quot;user&quot;,&quot;userId&quot;:&quot;536f08e5-0f63-458d-b0b2-<br>                    990735979a6b&quot;,&quot;ipAddress&quot;:&quot;192.168.65.1&quot;,&quot;start&quot;:1722259486000,</pre><p>For Postman follow the instructions in Postman section here: <a href="https://medium.com/@jawadrashid/accessing-keycloak-api-using-node-js-and-aws-lambda-part-1-5782437afaf2#8016">https://medium.com/@jawadrashid/accessing-keycloak-api-using-node-js-and-aws-lambda-part-1-5782437afaf2#8016</a></p><h3>Deploying the AWS Lambda To Amazon AWS</h3><p>Follow the instructions given in guide by aws here: <a href="https://docs.aws.amazon.com/lambda/latest/dg/java-image.html#java-image-instructions">https://docs.aws.amazon.com/lambda/latest/dg/java-image.html#java-image-instructions</a>. In <strong>Using an AWS base image for Java</strong> section go to part <strong>Deploying the image</strong> and follow the instructions. I don’t have a remote keycloak server running so I did not test deploying to AWS Lambda remotely but I tested the lambda functions locally through docker. Following the section below will deploy to aws lambda:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/972/1*nlr1cGCXUOqaa0WLRg-9Aw.png" /></figure><h3>Final Remarks</h3><p>You can find the whole code at: <a href="https://github.com/jawadrashid2011/aws-lambda-final">https://github.com/jawadrashid2011/aws-lambda-final</a>. Also find he first Part 1 here: <a href="https://medium.com/@jawadrashid/accessing-keycloak-api-using-node-js-and-aws-lambda-part-1-5782437afaf2">https://medium.com/@jawadrashid/accessing-keycloak-api-using-node-js-and-aws-lambda-part-1-5782437afaf2</a></p><h3>Resources</h3><ul><li>Accessing Keycloak API using Node.js and AWS Lambda — Part 1 <a href="https://medium.com/@jawadrashid/accessing-keycloak-api-using-node-js-and-aws-lambda-part-1-5782437afaf2">https://medium.com/@jawadrashid/accessing-keycloak-api-using-node-js-and-aws-lambda-part-1-5782437afaf2</a></li><li>Github code for this tutorial: <a href="https://github.com/jawadrashid2011/aws-lambda-final">https://github.com/jawadrashid2011/aws-lambda-final</a></li><li>AWS Lambda Documentation for Deploying Lambda Function with container images in Java: <a href="https://docs.aws.amazon.com/lambda/latest/dg/java-image.html">https://docs.aws.amazon.com/lambda/latest/dg/java-image.html</a></li><li><a href="https://medium.com/@jawadrashid/implementing-keycloak-event-listener-spi-service-provider-interfaces-1f01ae819e8d">My previous tutorial on how to setup implement Keycloak SPI Event Listener using docker</a></li><li><a href="https://medium.com/@jawadrashid/how-to-use-rest-api-for-keycloak-admin-through-node-js-app-cfac0372eb4a">How to use REST API in Keycloak written by me</a></li><li>Keycloak Java Classes Documentation: <a href="https://www.keycloak.org/docs-api/25.0.2/javadocs/">https://www.keycloak.org/docs-api/25.0.2/javadocs/</a></li><li>Keycloak Java Baeldung tutorial on Search Users with keycloak in Java Spring: <a href="https://www.baeldung.com/java-keycloak-search-users">https://www.baeldung.com/java-keycloak-search-users</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=198e4e418707" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Accessing Keycloak API using Node.js and AWS Lambda — Part 1]]></title>
            <link>https://medium.com/@jawadrashid/accessing-keycloak-api-using-node-js-and-aws-lambda-part-1-5782437afaf2?source=rss-c13478e3b633------2</link>
            <guid isPermaLink="false">https://medium.com/p/5782437afaf2</guid>
            <category><![CDATA[docker]]></category>
            <category><![CDATA[nodejs]]></category>
            <category><![CDATA[aws-lambda]]></category>
            <category><![CDATA[docker-compose]]></category>
            <category><![CDATA[keycloak]]></category>
            <dc:creator><![CDATA[Jawad Rashid]]></dc:creator>
            <pubDate>Mon, 29 Jul 2024 13:50:23 GMT</pubDate>
            <atom:updated>2024-07-29T15:00:25.970Z</atom:updated>
            <content:encoded><![CDATA[<h3>Introduction</h3><p>In this article I will use the docker image I created in the following tutorial <a href="https://medium.com/@jawadrashid/implementing-keycloak-event-listener-spi-service-provider-interfaces-1f01ae819e8d">https://medium.com/@jawadrashid/implementing-keycloak-event-listener-spi-service-provider-interfaces-1f01ae819e8d</a> and enhance it to use AWS lambda to interact with this keycloak server using lambda. I will write Java and NodeJS versions of my code in AWS lambda to:</p><ol><li>Get all active sessions for a user</li><li>Terminate all active sessions for an agent</li></ol><p>This is part 1 discussing how to write code in Node.JS. In next part we will discuss using Java code.</p><h3>Table Of Contents</h3><ul><li><a href="#7f72">Introduction</a></li><li><a href="#730a">Docker Setup</a></li><li><a href="#7e1e">Setting up Keycloak</a></li><li><a href="#1640">Introduction to Lambda NodeJS</a></li><li><a href="#bab9">Using AWS base image for Node.js</a></li><li><a href="#9c49">Creating Keycloak AWS function in Node.js to connect to Keycloak and perform our actions</a></li><li><a href="#8016">How to test our lambda function</a></li><li><a href="#6f9d">Deploying the AWS Lambda To Amazon AWS</a></li><li><a href="#6f8c">Final Thoughts</a></li><li><a href="#d11e">Resources</a></li></ul><h3>Docker Setup</h3><p>Here is the docker-compose.yaml for this app. There are many differences from the last tutorial because there are containers for running lambda code in nodeJs. I will explain the lambda code shortly but here is docker-compose.yaml in root of the setup.</p><pre>services:<br>  keycloak_demo:<br>    image: quay.io/keycloak/keycloak:25.0.2<br>    command: start-dev<br>    environment:<br>      KC_DB: postgres<br>      KC_DB_URL_HOST: postgres_keycloak_demo<br>      KC_DB_URL_DATABASE: keycloak<br>      KC_DB_PASSWORD: password<br>      KC_DB_USERNAME: keycloak<br>      KC_DB_SCHEMA: public<br>      KEYCLOAK_ADMIN: admin<br>      KEYCLOAK_ADMIN_PASSWORD: admin<br>    ports:<br>      - &quot;8890:8080&quot;<br>    depends_on:<br>      postgres_keycloak_demo:<br>        condition: service_healthy<br>    networks:<br>      - keycloak_demo_dev_network<br><br>  postgres_keycloak_demo:<br>    image: postgres:16.3<br>    command: postgres -c &quot;max_connections=200&quot;<br>    volumes:<br>      - pgdata_keycloak_data:/var/lib/postgresql/data<br>    environment:<br>      POSTGRES_DB: keycloak<br>      POSTGRES_USER: keycloak<br>      POSTGRES_PASSWORD: password<br>    healthcheck:<br>      test: &quot;exit 0&quot;<br>    ports:<br>      - &quot;5436:5432&quot;<br>    networks:<br>      - keycloak_demo_dev_network<br><br>  lambda-node:<br>    build: ./lambda-node<br>    ports: <br>      - &quot;9000:8080&quot;<br>    depends_on:<br>      - keycloak_demo<br>    networks:<br>      - keycloak_demo_dev_network<br><br>      <br>volumes:<br>  pgdata_keycloak_data:<br>networks:<br>  keycloak_demo_dev_network:<br>    driver: bridge<br></pre><p>Let me discuss some things about the docker file. There are 3 services one for keycloak named <strong>keycloak_demo</strong>, another for postgresql named <strong>postgres_keycloak_demo</strong>, and lastly one service for Node.JS lambda which I will explain later.</p><p>The configuration for Keycloak is very standard we are defining the Postgresql credentials for Keycloak to connect to, also we have set up admin username and password. Also, Keycloak internally runs on Port <strong>8080</strong> but I have mapped it to port 8890 to avoid conflicts with other services in my local machine.</p><p>Postgresql configuration is standard and follows the Keycloak docker guide.</p><ul><li>One note is that I choose to use development version of Keycloak and have not enabled SSL to make the setup easy.</li><li>I should note that one playlist I found very useful for docker is from YouTube channel named code215 here: <a href="https://www.youtube.com/playlist?list=PLQZfys2xO5kgpa9-qpJly78d-t7_Fnjec">https://www.youtube.com/playlist?list=PLQZfys2xO5kgpa9-qpJly78d-t7_Fnjec</a>. This series is very good to learn docker and keycloak and also for implementing SSL, using nginx and using infinispan.</li></ul><p>All the code is available at: <a href="https://github.com/jawadrashid2011/aws-lambda-final">https://github.com/jawadrashid2011/aws-lambda-final</a></p><h3>Setting up Keycloak</h3><p>I am assuming that you have already created a realm, and created a default user as described in guide here <a href="https://www.keycloak.org/getting-started/getting-started-docker">https://www.keycloak.org/getting-started/getting-started-docker</a> which is demo in my case for realm name and user for user.</p><p>Additionally i created 2 more users for testing purposes. Passwords needs to be set up for all 3 accounts.</p><p>Additionally you need to create a client under your <strong>master </strong>realm which I named demo-client, uncheck ‘Standard Flow’ and ‘Direct Access Grant’ options, check Client authentication (which will turn on Service account roles) and check Authorization. See screenshot below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Ch-YL8_HG8RdpftedXAouQ.png" /><figcaption>Creating client</figcaption></figure><p>We will use the name we set as client name and client secret can be found in credentials tab for the client we created.</p><h3>Introduction to Lambda NodeJS</h3><p>Instructions are given below for testing Lambda locally and deploying it on AWS Lambda:</p><ul><li>Install AWS CLI here: <a href="https://docs.aws.amazon.com/cli/latest/userguide/getting-started-install.html">https://docs.aws.amazon.com/cli/latest/userguide/getting-started-install.html</a>. There are instructions for Linux, MacOS, and Windows. This is needed if you need to deploy your lambda functions directly to AWS lambda.</li></ul><p>What is AWS Lambda? Well if you want to know you might find this YouTube video by Simplilearn useful:</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2F97q30JjEq9Y%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3D97q30JjEq9Y&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2F97q30JjEq9Y%2Fhqdefault.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/29466009651b4e56fee8fee65a6ab225/href">https://medium.com/media/29466009651b4e56fee8fee65a6ab225/href</a></iframe><p>AWS Lambda Node.js documentation describes the steps on how to deploy Node.js Lambda functions with container images here: <a href="https://docs.aws.amazon.com/lambda/latest/dg/nodejs-image.html">https://docs.aws.amazon.com/lambda/latest/dg/nodejs-image.html</a></p><p>The reason I chose to deploy the Lambda function to docker service is because I wanted to be able to test locally the Lambda function before deploying to AWS Lambda. Using docker image helped me setup a container quickly and test Lambda functions locally with my docker Keycloak instance.</p><h3>Using AWS base image for Node.js</h3><p>In the guide <a href="https://docs.aws.amazon.com/lambda/latest/dg/nodejs-image.html">https://docs.aws.amazon.com/lambda/latest/dg/nodejs-image.html</a> I chose to select AWS base image for Node.js as you can start from here and just deploy your lambda function to this container and you can test it quickly.</p><p>I chose to follow the instructions described in section named “<a href="https://docs.aws.amazon.com/lambda/latest/dg/nodejs-image.html#nodejs-image-instructions">Using an AWS base image for Node.js</a>”. I am going to note down the steps I used to create the service for lambda for Node.js using AWS node image. The code I have provided already has the instructions integrated into it so if you are using my code you don’t need to follow along.</p><ol><li>Create a folder and go into it</li></ol><pre>mkdir example<br>cd example</pre><p>2. Initialize npm and select the defaults.</p><pre>npm init</pre><p>3. Create a file named index.js which will contain your lambda function code. Here is the sample code to test your lambda instance which outputs Hello From Lambda!.</p><pre>exports.handler = async (event) =&gt; {<br>    const response = {<br>        statusCode: 200,<br>        body: JSON.stringify(&#39;Hello from Lambda!&#39;),<br>    };<br>    return response;<br>};</pre><p>4. Create a dockerfile and put the following code. Basically we are using the aws lambda Node.js version 20 image and copying our code i.e. index.js to the root and running the lambda function in the container using CMD.</p><pre>FROM public.ecr.aws/lambda/nodejs:20<br><br># Copy function code<br>COPY index.js ${LAMBDA_TASK_ROOT}<br>  <br># Set the CMD to your handler (could also be done as a parameter override outside of the Dockerfile)<br>CMD [ &quot;index.handler&quot; ]</pre><p>5. Build the image</p><pre>docker build --platform linux/amd64 -t docker-image:test .</pre><p>6. Test the docker image by running the docker container.</p><pre>docker run --platform linux/amd64 -p 9000:8080 docker-image:test</pre><p>7. With your docker container running with your lambda function deployed just test the code by using Powershell or Linux/macOS commands given in the guide above. I am giving two commands for powershell below:</p><p>For testing the lambda function without input:</p><pre>Invoke-WebRequest -Uri &quot;http://localhost:9000/2015-03-31/functions/function/invocations&quot; -Method Post -Body &#39;{}&#39; -ContentType &quot;application/json&quot;</pre><p>For testing the lambda function with payload input</p><pre>Invoke-WebRequest -Uri &quot;http://localhost:9000/2015-03-31/functions/function/invocations&quot; -Method Post -Body &#39;{&quot;payload&quot;:&quot;hello world!&quot;}&#39; -ContentType &quot;application/json&quot;</pre><p>In the sample code case the payload input won’t give any different output as it is not using input in input variable but we can use the event in our lambda function to process the input to lambda function.</p><p>8. Stop the container by running commands where containerid is the id of the container for lambda in docker ps.</p><pre>docker ps<br>docker kill containerid</pre><p>9. Finally I am not going to give steps but you can follow the steps in <strong>“Deploying the image”</strong> to deploy the lambda function to AWS lambda in guide: <a href="https://docs.aws.amazon.com/lambda/latest/dg/nodejs-image.html#nodejs-image-instructions">https://docs.aws.amazon.com/lambda/latest/dg/nodejs-image.html#nodejs-image-instructions</a>.</p><ul><li>It basically involves use aws ecr to authenticate docker cli to Amazon ECR registry, creating the docker repository in Amazon ECR, tagging the docker image, and pushing it.</li><li>Once that is done creating the lambda function giving it our image url, and testing the function using aws lambda invoke method described.</li></ul><h3>Creating Keycloak AWS function in Node.js to connect to Keycloak and perform our actions</h3><p>Basically the above instructions helped to create a Node.js AWS lambda container to deploy and test the lambda function code. Now I will customize it to work with our docker setup and also I will share the code for connecting to Keycloak to perform our tasks.</p><p>Before we start I will be using keycloak admin client library (<a href="https://www.npmjs.com/package/@keycloak/keycloak-admin-client">https://www.npmjs.com/package/@keycloak/keycloak-admin-client</a>) which allows to write code in Node.JS to connect to Keycloak using REST protocol and perform a lot of actions. I have written a guide for this before in my previous tutorial here: <a href="https://medium.com/@jawadrashid/how-to-use-rest-api-for-keycloak-admin-through-node-js-app-cfac0372eb4a#a179">https://medium.com/@jawadrashid/how-to-use-rest-api-for-keycloak-admin-through-node-js-app-cfac0372eb4a#a179</a> which showed how to connect to Keycloak using Node.JS app.</p><ul><li>First let’s see review the service we added in our docker compose file in the start which is needed to test Node.js Lambda code locally.</li></ul><p>Part of docker-compose.yaml dealing with node lambda service.</p><pre>lambda-node:<br>    build: ./lambda-node<br>    ports: <br>      - &quot;9000:8080&quot;<br>    depends_on:<br>      - keycloak_demo<br>    networks:<br>      - keycloak_demo_dev_network</pre><p>Dockerfile for lambda node application.</p><pre>FROM public.ecr.aws/lambda/nodejs:20<br><br>COPY getSessions.mjs ${LAMBDA_TASK_ROOT}<br>COPY terminateSessions.mjs ${LAMBDA_TASK_ROOT}<br><br>COPY ./node_modules ${LAMBDA_TASK_ROOT}/node_modules<br><br>CMD [ &quot;getSessions.handler&quot; ]<br># CMD [ &quot;terminateSessions.handler&quot; ]</pre><p>package.json</p><pre>{<br>  &quot;name&quot;: &quot;lambda-node&quot;,<br>  &quot;version&quot;: &quot;1.0.0&quot;,<br>  &quot;description&quot;: &quot;&quot;,<br>  &quot;lambda1&quot;: &quot;getSessions.mjs&quot;,<br>  &quot;lambda2&quot;: &quot;terminateSessions.mjs&quot;,<br>  &quot;main&quot;: &quot;getSessions.mjs&quot;,<br>  &quot;type&quot;: &quot;module&quot;,<br>  &quot;scripts&quot;: {<br>    &quot;test&quot;: &quot;echo \&quot;Error: no test specified\&quot; &amp;&amp; exit 1&quot;<br>  },<br>  &quot;author&quot;: &quot;&quot;,<br>  &quot;license&quot;: &quot;ISC&quot;,<br>  &quot;dependencies&quot;: {<br>    &quot;@keycloak/keycloak-admin-client&quot;: &quot;25.0.2&quot;<br>  }<br>}</pre><ul><li>Basically we in docker-compose I have created a service which uses dockerfile for building the aws lambda node.js docker image. We will discuss Dockerfile shortly.</li><li>As the node.js aws lambda code deploys locally on 8080 I have mapped it to port 9000 externally as I will call through Postman to test code.</li><li>Also as it connects to keycloak I have added dependency on keycloak_demo service.</li><li>The network is the same that is being used by Keycloak and Postgresql in docker-compose.</li><li>Now coming to the Dockerfile. I have modified the dockerfile created in the aws lambda steps I described in previous section.</li><li>I have created 2 files 1 for getting sessions and 1 for terminating sessions named getSessions.mjs and terminateSessions.mjs. The reason I used mjs extension was because when I used js file it was giving me errors for running code outside module and creating mjs resolved that.</li><li>Also, If you get any problems you should delete node_modules folder and use <strong>npm install</strong> command to install node_modules for your machine.</li><li>Package.json is standard except I have described dependency of keycloak-admin-client to connect Node.js to Keycloak and main is important which I will discuss when running the code. <strong>It should be getSessions.mjs for getting sessions and terminateSessions.mjs for terminating sessions.</strong></li><li><strong>Lambda code for getSessions.mjs</strong></li></ul><pre>import KcAdminClient from &quot;@keycloak/keycloak-admin-client&quot;;<br><br>const BASE_URL = process.env.BASE_URL || &quot;http://keycloak_demo:8080&quot;;<br>const KEYCLOAK_GRANT_TYPE = process.env.KEYCLOAK_GRANT_TYPE || &quot;client_credentials&quot;;<br>const KEYCLOAK_CLIENT_ID = process.env.KEYCLOAK_CLIENT_ID || &quot;demo-client&quot;;<br>const KEYCLOAK_CLIENT_SECRET = process.env.KEYCLOAK_CLIENT_SECRET || &quot;CLIENT_SECRET_GOES_HERE&quot;;<br>const KEYCLOAK_REALM = process.env.KEYCLOAK_REALM || &quot;Demo&quot;;<br><br><br>export const handler = async (event) =&gt; {  <br>  const username = event.username || &quot;&quot;;<br>  const realmName = event.realm || KEYCLOAK_REALM;<br><br>  /* Setting Environment and defaults */<br>  <br>  let output = [];<br><br>  const kcAdminClient = new KcAdminClient({<br>    baseUrl: BASE_URL,<br>  });<br>  <br>  await kcAdminClient.auth({<br>    grantType: KEYCLOAK_GRANT_TYPE,<br>    clientId: KEYCLOAK_CLIENT_ID,<br>    clientSecret: KEYCLOAK_CLIENT_SECRET,<br>  });<br>  <br>  // List first page of users<br>  kcAdminClient.setConfig({<br>    realmName: realmName,<br>  });<br>  <br>  const current_user = await kcAdminClient.users.find({<br>    username: username,<br>    exact: true,<br>  });<br>  // console.log(&quot;User&quot;, current_user);<br>  if (current_user.length == 0) {<br>    // console.log(&quot;No User Found&quot;);<br>    output = &quot;No User Found&quot;;<br>  } else {<br>    const sessions = await kcAdminClient.users.listSessions({<br>      id: current_user[0].id,<br>    });<br>    // console.log(&quot;Sessions&quot;, sessions);<br>    output = sessions;<br>  }<br><br>  const response = {<br>    statusCode: 200,<br>    body: output,<br>  };<br>  return response;<br>};</pre><ul><li>This code uses <strong>@keycloak/keycloak-admin-client </strong>library to connect to Keycloak.</li><li>One important note is that for the client you created which is defined in <strong>master</strong> realm needs to have service roles added: view-clients, manage-users, query-user, view-users for both master and the realm you want to get sessions from which in my case is named “Demo” as shown in following screenshot</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*hp55bEsaQ_nYbbFtXnNLaw.png" /></figure><ul><li>The first part of the above script is setting up the environment variables/default values. One thing to note is that <strong>BASE_URL </strong>we need to connect to keycloak. Keycloak is not running here on localhost from within docker instead we need to use the ip address of the keycloak server. As we have defined the keycloak_demo service from within docker-compose.yaml we can use <a href="http://keycloak_demo/">http://keycloak_demo</a> as the url as keycloak_demo will automatically translate it ip address. Also, I am giving port 8080 and not the external port of keycloak_demo which in my case is 8890 because we are within docker and on same network and when we go to ip address keycloak_demo we are accessing local service so we will use 8080.</li><li>In handler we get an <strong>event </strong>object which is AWS lambda passes the payload to this variable. In the following code I am getting username send when calling the lambda function and optionally if realm is set then that is set also.</li></ul><pre>const username = event.username || &quot;&quot;;<br>const realmName = event.realm || KEYCLOAK_REALM;</pre><ul><li><strong>kcAdminClient.auth</strong> authenticates to the keycloak server.</li><li>Next the following code sets the <strong>realmName </strong>for further queries to the realm we are interested in interacting with which in my case is named <strong>Demo</strong>.<strong> </strong>When we will get sessions or users it will use the realmName which is either Demo or the one that is passed by lambda payload.</li><li>First we find the user from the realm using the following code. I found the code by first looking at the Keycloak admin REST api here: <a href="https://www.keycloak.org/docs-api/25.0.2/rest-api/index.html#_users">https://www.keycloak.org/docs-api/25.0.2/rest-api/index.html#_users</a>. Then we want to find by username which we can use the method GET /admin/realms/{realm}/user. As he have already set the realm we only need to give username parameter. Also, I looked at <a href="https://github.com/keycloak/keycloak/tree/main/js/libs/keycloak-admin-client">https://github.com/keycloak/keycloak/tree/main/js/libs/keycloak-admin-client</a> github and found the code below.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Ok1prxF9ev9mMKBudPgmbg.png" /></figure><pre>const current_user = await kcAdminClient.users.find({<br>    username: username,<br>    exact: true,<br>  });</pre><ul><li>Then if it is found that we get all sessions for that user by using users.listSessions by giving user id which we got from previous step.</li></ul><pre>const sessions = await kcAdminClient.users.listSessions({<br>      id: current_user[0].id,<br>    });</pre><ul><li>Finally I return the sessions for that user in body.</li><li><strong>Lambda code for terminateSession</strong></li></ul><pre>import KcAdminClient from &quot;@keycloak/keycloak-admin-client&quot;;<br><br>const BASE_URL = process.env.BASE_URL || &quot;http://keycloak_demo:8080&quot;;<br>const KEYCLOAK_GRANT_TYPE = process.env.KEYCLOAK_GRANT_TYPE || &quot;client_credentials&quot;;<br>const KEYCLOAK_CLIENT_ID = process.env.KEYCLOAK_CLIENT_ID || &quot;demo-client&quot;;<br>const KEYCLOAK_CLIENT_SECRET = process.env.KEYCLOAK_CLIENT_SECRET || &quot;CLIENT_SECRET_GOES_HERE&quot;;<br>const KEYCLOAK_REALM = process.env.KEYCLOAK_REALM || &quot;Demo&quot;;<br><br><br><br>export const handler = async (event) =&gt; {  <br>  const username = event.username || &quot;&quot;;<br>  const realmName = event.realm || KEYCLOAK_REALM;<br><br>  /* Setting Environment and defaults */<br>  <br>  let output = &quot;&quot;;<br><br>  const kcAdminClient = new KcAdminClient({<br>    baseUrl: BASE_URL,<br>  });<br>  <br>  await kcAdminClient.auth({<br>    grantType: KEYCLOAK_GRANT_TYPE,<br>    clientId: KEYCLOAK_CLIENT_ID,<br>    clientSecret: KEYCLOAK_CLIENT_SECRET,<br>  });<br>  <br>  // List first page of users<br>  kcAdminClient.setConfig({<br>    realmName: realmName,<br>  });<br>  <br>  const current_user = await kcAdminClient.users.find({<br>    username: username,<br>    exact: true,<br>  });<br>  // console.log(&quot;User&quot;, current_user);<br>  if (current_user.length == 0) {<br>    output = &quot;No User Found&quot;;<br>    // console.log(output);<br>  } else {<br>    const sessions = await kcAdminClient.users.listSessions({<br>      id: current_user[0].id,<br>    });<br>    output = sessions;<br>    if (sessions.length == 0) {<br>      output = &quot;No Sessions Found&quot;;<br>      // console.log(output);<br>    } else {<br>      await kcAdminClient.users.logout({<br>        id: current_user[0].id,<br>      });<br>      output = &quot;Logout succesful. Total sessions terminated: &quot; + sessions.length;<br>      // console.log(output);<br>      <br>    }<br>  }<br><br>  const response = {<br>    statusCode: 200,<br>    body: output,<br>  };<br>  return response;<br>};</pre><ul><li>The code for terminateSessions is similar excpet we use the following code to logout the user by giving user id</li></ul><pre>await kcAdminClient.users.logout({<br>  id: current_user[0].id,<br>});</pre><h3>How to test our lambda function</h3><p>In our docker file we have defined which function to run. To test getSessions I will keep <strong>CMD [ “getSessions.handler” ] </strong>uncommented and comment out terminateSessions CMD command. Also in package.json main should be set to <strong>“getSessions.mjs” </strong>like below</p><pre>&quot;main&quot;: &quot;getSessions.mjs&quot;,</pre><ul><li>Let’s first fire up our docker containers</li><li>Execute the following commands:</li></ul><pre>docker-compose down --remove-orphans<br>docker-compose up --build -d</pre><ul><li>This will build all 3 services: keycloak_demo, postgres_keycloak_demo and lambda-node.</li><li>You will have to wait till Keycloak has started and go to <a href="http://localhost:8890/admin">http://localhost:8890/admin</a> to access the admin and give username/password to login which in my case is admin/admin</li><li>If this is first time you are running docker for this project then create 2 users and the client for my master as described in section <strong>Setting up Keycloak</strong>.</li><li>Also, open up a new tab and go to <a href="http://localhost:8890/realms/Demo/account">http://localhost:8890/realms/Demo/account</a> where Demo is your realm name.</li><li>Login with the user you created which is in my case is named <strong>user</strong></li><li>Now we need to test our lambda Node.js function. We can do this by either running Postman request or running command in Powershell. Let me discuss each option</li></ul><p><strong>For Powershell:</strong></p><p>Run the following command. Our server is running on localhost on port 9000. This command is from the aws lambda documetnation for Node.js <a href="https://docs.aws.amazon.com/lambda/latest/dg/nodejs-image.html">https://docs.aws.amazon.com/lambda/latest/dg/nodejs-image.html</a>. Important thing is the payload/body<strong> ‘{“username”: “user”, “realm”: “Demo”}’</strong>. Here username is the username of user we want to get sessions for and realm is the realm name where user exists. Here realm is optional. If not given it will use KEYCLOAK_REALM.</p><pre>Invoke-WebRequest -Uri &quot;http://localhost:9000/2015-03-31/functions/function/invocations&quot; -Method Post -Body &#39;{&quot;username&quot;: &quot;user&quot;, &quot;realm&quot;: &quot;Demo&quot;}&#39; -ContentType &quot;application/json&quot;</pre><p>You can find the macOS/linux command from the aws docs given above.</p><p>Response will be like this:</p><pre> {&quot;statusCode&quot;:200,&quot;body&quot;:[{&quot;id&quot;:&quot;b1f61547-8860-4de0-9e3c-3c5f88afd650&quot;,&quot;username&quot;:&quot;user&quot;,&quot;userId&quot;:&quot;536f08e5-0f63-458d-b0b2-<br>                    990735979a6b&quot;,&quot;ipAddress&quot;:&quot;192.168.65.1&quot;,&quot;start&quot;:1722259486000,&quot;lastAccess&quot;:1...</pre><p>If there are multiple sessions for same user it will be in json comma separated. Here there is only 1 session for user currently.</p><p><strong>For Postman</strong></p><ul><li>Create a new request</li><li>Set Request type to <strong>POST</strong></li><li>Set Request url to <a href="http://localhost:9000/2015-03-31/functions/function/invocations">http://localhost:9000/2015-03-31/functions/function/invocations</a></li><li>In Headers set <strong>Content-Type </strong>to <strong>application/json</strong></li><li>Go to Body section, set the type to raw and from dropdown select JSON</li><li>Add in body the following code. Realm is optional:</li></ul><pre>{<br>    &quot;username&quot;: &quot;user&quot;,<br>    &quot;realm&quot;: &quot;Demo&quot;<br>}</pre><ul><li>Click send and you will get response like below:</li></ul><pre>{&quot;statusCode&quot;:200,&quot;body&quot;:<br>[{&quot;id&quot;:&quot;ec107b9d-734d-4690-9d95-8845aa417be8&quot;,<br>&quot;username&quot;:&quot;user&quot;,<br>&quot;userId&quot;:&quot;536f08e5-0f63-458d-b0b2-990735979a6b&quot;,<br>&quot;ipAddress&quot;:&quot;192.168.65.1&quot;,<br>&quot;start&quot;:1722256373000,<br>&quot;lastAccess&quot;:1722256375000,&quot;rememberMe&quot;:false,&quot;clients&quot;:{&quot;64486b68-2e40-4adc-9f31-eae5c3491501&quot;:&quot;account-console&quot;},&quot;transientUser&quot;:false}]}</pre><p><strong>How to test terminateSessions</strong></p><ul><li>In package.json inside lambda-node change “main” to “terminateSessions.mjs” like below:</li></ul><pre>&quot;main&quot;: &quot;terminateSessions.mjs&quot;,</pre><ul><li>In Dockerfile comment CMD for getSessions and remove comment from CMD for terminateSessions</li></ul><pre># CMD [ &quot;getSessions.handler&quot; ]<br>CMD [ &quot;terminateSessions.handler&quot; ]</pre><ul><li>If docker is not running then use the same command to run the docker containers</li></ul><pre>docker-compose down --remove-orphans<br>docker-compose up --build -d</pre><ul><li>If docker is already running and you make changes to lambda-node service then just run the following code to recreate the lambda-node service with new changes without restarting Keycloak or db</li></ul><pre>docker-compose stop lambda-node<br>docker-compose up lambda-node --build -d</pre><ul><li>Next, test it similarly as you did for getSessions by executing command in Powershell or Postman without any change.</li><li>If there is any session for user that user will be logged out and you will get the following response which tells you how many sessions for the user is terminated:</li></ul><pre>{&quot;statusCode&quot;:200,&quot;body&quot;:&quot;Logout succesful. Total sessions terminated: 1&quot;}</pre><h3>Deploying the AWS Lambda To Amazon AWS</h3><p>Follow the instructions given in guide by aws here: <a href="https://docs.aws.amazon.com/lambda/latest/dg/nodejs-image.html#nodejs-image-instructions">https://docs.aws.amazon.com/lambda/latest/dg/nodejs-image.html#nodejs-image-instructions</a>. In <strong>Using an AWS base image for Node.js</strong> section go to part <strong>Deploying the image</strong> and follow the instructions. I don’t have a remote keycloak server running so I did not test deploying to AWS Lambda remotely but I tested the lambda functions locally through docker. Following the section below will deploy to aws lambda:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/968/1*JW1tcl7UsVDWd5dXKhFd3w.png" /></figure><h3>Final Thoughts</h3><p>This part discusses how to create Node.JS AWS lambda function, test it locally in docker and deploy it. In next part here: <a href="https://medium.com/@jawadrashid/accessing-keycloak-api-using-java-and-aws-lambda-part-2-198e4e418707">https://medium.com/@jawadrashid/accessing-keycloak-api-using-java-and-aws-lambda-part-2-198e4e418707</a> we will discuss on how to do the same with Java lambda function. I will enhance the existing code with services for Java and Java app. The full code is available at: <a href="https://github.com/jawadrashid2011/aws-lambda-final">https://github.com/jawadrashid2011/aws-lambda-final</a></p><h3>Resources</h3><ul><li>Github code for this tutorial: <a href="https://github.com/jawadrashid2011/aws-lambda-final">https://github.com/jawadrashid2011/aws-lambda-final</a></li><li><a href="https://medium.com/@jawadrashid/implementing-keycloak-event-listener-spi-service-provider-interfaces-1f01ae819e8d">My previous tutorial on how to setup implement Keycloak SPI Event Listener using docker</a></li><li><a href="https://medium.com/@jawadrashid/how-to-use-rest-api-for-keycloak-admin-through-node-js-app-cfac0372eb4a">How to use REST API in Keycloak written by me</a>.</li><li>Setting up AWS cli: <a href="https://docs.aws.amazon.com/cli/latest/userguide/getting-started-install.html">https://docs.aws.amazon.com/cli/latest/userguide/getting-started-install.html</a></li><li>AWS Lambda Documentation for Deploying Lambda Function with container images: <a href="https://docs.aws.amazon.com/lambda/latest/dg/nodejs-image.html">https://docs.aws.amazon.com/lambda/latest/dg/nodejs-image.html</a></li><li>Great Keycloak with docker YouTube playlist by code215: <a href="https://www.youtube.com/playlist?list=PLQZfys2xO5kgpa9-qpJly78d-t7_Fnjec">https://www.youtube.com/playlist?list=PLQZfys2xO5kgpa9-qpJly78d-t7_Fnjec</a></li><li>AWS Lambda Tutorial For Beginners by Simplilearn: <a href="https://www.youtube.com/watch?v=97q30JjEq9Y">https://www.youtube.com/watch?v=97q30JjEq9Y</a></li><li>Keycloak Admin Client Node.JS Client Library: <a href="https://www.npmjs.com/package/@keycloak/keycloak-admin-client">https://www.npmjs.com/package/@keycloak/keycloak-admin-client</a></li><li>Keycloak REST Admin API: <a href="https://www.keycloak.org/docs-api/25.0.2/rest-api/index.html#_users">https://www.keycloak.org/docs-api/25.0.2/rest-api/index.html#_users</a></li><li>Keycloak admin Client Node.JS github documentation: <a href="https://github.com/keycloak/keycloak/tree/main/js/libs/keycloak-admin-client">https://github.com/keycloak/keycloak/tree/main/js/libs/keycloak-admin-client</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5782437afaf2" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Implementing Keycloak Event Listener SPI (Service Provider Interfaces)]]></title>
            <link>https://medium.com/@jawadrashid/implementing-keycloak-event-listener-spi-service-provider-interfaces-1f01ae819e8d?source=rss-c13478e3b633------2</link>
            <guid isPermaLink="false">https://medium.com/p/1f01ae819e8d</guid>
            <category><![CDATA[keycloak]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[spi]]></category>
            <category><![CDATA[docker]]></category>
            <category><![CDATA[java]]></category>
            <dc:creator><![CDATA[Jawad Rashid]]></dc:creator>
            <pubDate>Wed, 10 Jul 2024 11:27:32 GMT</pubDate>
            <atom:updated>2024-07-25T14:59:37.690Z</atom:updated>
            <content:encoded><![CDATA[<p>Keycloak is an open source identity and access management solution. In this article I will explore and define steps of implementing Event Listener SPI in Java in Keycloak to catch events happening in Keycloak.</p><h3>Table Of Contents</h3><ul><li><a href="#7eed">Introduction</a></li><li><a href="#8a83">Implementing SPI in Java</a></li><li><a href="#1f97">Dockerized Keycloak Setup</a></li><li><a href="#522a">Resources</a></li></ul><h3>Introduction</h3><p>You can implement a SPI like authentication, Action Token, Event Listener and much more. You can read more about SPI in Keycloak here <a href="https://www.keycloak.org/docs/latest/server_development/#_providers">https://www.keycloak.org/docs/latest/server_development/#_providers</a></p><p>Basically there is a long list of providers that Keycloak provides to provide custom code or extend already existing providers. Keycloak already provides a lot of providers for different parts of the software. You can provide your own provider to handle a part of the software you need access to.</p><p>If you have Keycloak already installed you can go to master realm and on the welcome page click on Provider Info page and you will see a list of SPI and providers for that SPI you can implement.</p><p>Keycloak logs and handles events like login, signup, sign out and much more through eventsListener SPI. I am going to implement that SPI by providing own code and including it in Keycloak in order to enable that SPI. eventsListener SPI capture admin and user events and I will handle successful login event from that.</p><p>There is a very good series for docker and Keycloak including implementing SPI on YouTube by a channel named code215 which includes implementing SPI in lesson 7. I would recommend following through all videos upto video 7 which will help you. The playlist is here: <a href="https://www.youtube.com/playlist?list=PLQZfys2xO5kgpa9-qpJly78d-t7_Fnjec">https://www.youtube.com/playlist?list=PLQZfys2xO5kgpa9-qpJly78d-t7_Fnjec</a> . I have used another tutorial which I have linked below which discusses how to do everything for implementing SPI.</p><h3>Implementing SPI in Java</h3><p>Looking into Keycloak Server Developer guide (<a href="https://www.keycloak.org/docs/latest/server_development/#_providers">https://www.keycloak.org/docs/latest/server_development/#_providers</a>) we can see that in order to implement an SPI we need 3 things:</p><ol><li>Provider class that implements the main login for the functionality.</li><li>ProviderFactory class that instantiates an object of Provider class we implemented in step 1.</li><li>A service configuration file which defines the exact factory we created in step 2 which Keycloak will use to get an object of our provider class.</li></ol><p>An excerpt from the guide:</p><blockquote>To implement an SPI you need to implement its ProviderFactory and Provider interfaces. You also need to create a service configuration file.</blockquote><p>The guide above shows an example of ThemeSelector Provider, factory and the configuration to implement that SPI.</p><p>In our case for eventsListener we need to implement the following files:</p><ol><li><a href="https://www.keycloak.org/docs-api/21.0.1/javadocs/org/keycloak/events/EventListenerProvider.html">EventsListenerProvider</a></li><li><a href="https://www.keycloak.org/docs-api/21.0.1/javadocs/org/keycloak/events/EventListenerProviderFactory.html">EventListenerProviderFactory</a></li><li>a file name org.keycloak.events.EventsListenerProviderFactory under src/main/resources/META-INF/services/</li></ol><p>I will be reusing steps and code from this medium article by Adwait Thattey <a href="https://medium.com/@adwaitthattey/building-an-event-listener-spi-plugin-for-keycloak-5bf9de1b0965">https://medium.com/@adwaitthattey/building-an-event-listener-spi-plugin-for-keycloak-5bf9de1b0965</a> which gives steps and detailed code for building Event Listener SPI for Keycloak. Have a look at that guide for more detailed understanding on how to implement event listener SPI.</p><ol><li>I will be using the <a href="https://www.eclipse.org/">eclipse IDE</a> in order to create the Java maven project for implementing SPI. If you want to follow along install the latest Eclipse version installing Eclipse for Java Developers from the installation.</li><li>Create an maven project in Eclipse (I selected simpe project — Skip archtectype selection) as I will be adding my own code in pom.xml</li><li>Give a group Id (com.example) and artifact Id (simple-event-listener) for example and keep packaging as jar. We will customize all of these settings through pom.xml</li><li>Now click finish. Click on pom.xml and edit it. Add the following code to pom.xml. I have changed some settings from the guide I gave above including the Keycloak version and some settings. I have set the version of keycloak-parent to 25.0.1 which is the latest keycloak version at the time of writing this article.</li></ol><pre>&lt;project xmlns=&quot;http://maven.apache.org/POM/4.0.0&quot; xmlns:xsi=&quot;http://www.w3.org/2001/XMLSchema-instance&quot;<br>         xsi:schemaLocation=&quot;http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd&quot;&gt;<br>    &lt;parent&gt;<br>        &lt;groupId&gt;org.keycloak&lt;/groupId&gt;<br>        &lt;artifactId&gt;keycloak-parent&lt;/artifactId&gt;<br>        &lt;version&gt;25.0.1&lt;/version&gt;<br>    &lt;/parent&gt;<br>    <br>    &lt;properties&gt;<br>     &lt;java.version&gt;1.8&lt;/java.version&gt;<br>     &lt;maven-jar-plugin.version&gt;3.1.1&lt;/maven-jar-plugin.version&gt;<br> &lt;/properties&gt;<br><br>    &lt;name&gt;REST Provider 1&lt;/name&gt;<br>    &lt;description/&gt;<br>    &lt;modelVersion&gt;4.0.0&lt;/modelVersion&gt;<br><br>    &lt;artifactId&gt;sample_event_listener&lt;/artifactId&gt;<br>    &lt;packaging&gt;jar&lt;/packaging&gt;<br><br>    &lt;dependencies&gt;<br>        &lt;dependency&gt;<br>            &lt;groupId&gt;org.keycloak&lt;/groupId&gt;<br>            &lt;artifactId&gt;keycloak-core&lt;/artifactId&gt;<br>            &lt;scope&gt;provided&lt;/scope&gt;<br>        &lt;/dependency&gt;<br>        &lt;dependency&gt;<br>            &lt;groupId&gt;org.keycloak&lt;/groupId&gt;<br>            &lt;artifactId&gt;keycloak-server-spi&lt;/artifactId&gt;<br>            &lt;scope&gt;provided&lt;/scope&gt;<br>        &lt;/dependency&gt;<br>        &lt;dependency&gt;<br>            &lt;groupId&gt;org.keycloak&lt;/groupId&gt;<br>            &lt;artifactId&gt;keycloak-server-spi-private&lt;/artifactId&gt;<br>            &lt;scope&gt;provided&lt;/scope&gt;<br>        &lt;/dependency&gt;<br>        &lt;dependency&gt;<br>            &lt;groupId&gt;org.keycloak&lt;/groupId&gt;<br>            &lt;artifactId&gt;keycloak-services&lt;/artifactId&gt;<br>            &lt;scope&gt;provided&lt;/scope&gt;<br>        &lt;/dependency&gt;<br>        &lt;dependency&gt;<br>            &lt;groupId&gt;org.keycloak&lt;/groupId&gt;<br>            &lt;artifactId&gt;keycloak-saml-core-public&lt;/artifactId&gt;<br>            &lt;scope&gt;provided&lt;/scope&gt;<br>        &lt;/dependency&gt;<br>        &lt;dependency&gt;<br>            &lt;groupId&gt;org.jboss.logging&lt;/groupId&gt;<br>            &lt;artifactId&gt;jboss-logging&lt;/artifactId&gt;<br>            &lt;scope&gt;provided&lt;/scope&gt;<br>        &lt;/dependency&gt;<br>        &lt;dependency&gt;<br>            &lt;groupId&gt;org.jboss.spec.javax.ws.rs&lt;/groupId&gt;<br>            &lt;artifactId&gt;jboss-jaxrs-api_2.1_spec&lt;/artifactId&gt;<br>        &lt;/dependency&gt;<br>    &lt;/dependencies&gt;<br><br>    &lt;build&gt;<br>        &lt;finalName&gt;sample-event-listener&lt;/finalName&gt;<br>        &lt;plugins&gt;<br>            &lt;plugin&gt;<br>                &lt;groupId&gt;org.apache.maven.plugins&lt;/groupId&gt;<br>                &lt;artifactId&gt;maven-compiler-plugin&lt;/artifactId&gt;<br>                &lt;configuration&gt;<br>                    &lt;source&gt;1.8&lt;/source&gt;<br>                    &lt;target&gt;1.8&lt;/target&gt;<br>                &lt;/configuration&gt;<br>            &lt;/plugin&gt;<br>            &lt;plugin&gt;<br>                &lt;groupId&gt;org.wildfly.plugins&lt;/groupId&gt;<br>                &lt;artifactId&gt;wildfly-maven-plugin&lt;/artifactId&gt;<br>                &lt;configuration&gt;<br>                    &lt;skip&gt;false&lt;/skip&gt;<br>                &lt;/configuration&gt;<br>            &lt;/plugin&gt;<br>        &lt;/plugins&gt;<br>    &lt;/build&gt;<br>&lt;/project&gt;</pre><p>You can customize any settings you want. I added additional config for maven-jar-plugin.version as I was having a problem due to bug in Eclipse. Next right click on your project name in package explorer → maven → update project so all dependencies are downloaded.</p><p>5. Create a package under src/main/java. I created the package named <strong>com.keycloaktesting.sampleeventlistenerprovider.proivder</strong>. You can set your package to whatever you want that is suitable.</p><p>6. Add SampleEventListenerProvider.java file under src/main/java/com.keycloaktesting.sampleeventlistenerprovider.proivder package. The contents of the file is as following. I have used the same code with some modifications from guide by Adwait Thattey.</p><pre>package com.keycloaktesting.sampleeventlistenerprovider.provider;<br><br>import java.util.Map.Entry;<br><br>import org.keycloak.events.Event;<br>import org.keycloak.events.EventListenerProvider;<br>import org.keycloak.events.admin.AdminEvent;<br><br>public class SampleEventListenerProvider implements EventListenerProvider {<br> <br> public SampleEventListenerProvider() {<br>  <br> }<br><br> @Override<br>    public void onEvent(Event event) {<br>  if(event.getType().toString() == &quot;LOGIN&quot;) {<br>   System.out.println(&quot;Event Occurred:&quot; + toString(event));<br>  }<br>    }<br><br>    @Override<br>    public void onEvent(AdminEvent adminEvent, boolean b) {<br><br>        System.out.println(&quot;Admin Event Occurred:&quot; + toString(adminEvent));<br>    }<br><br>    @Override<br>    public void close() {<br><br>    }<br> <br> private String toString(Event event) {<br><br>        StringBuilder sb = new StringBuilder();<br><br>        sb.append(&quot;Event FOUND&quot;);<br><br>        sb.append(&quot;, type=&quot;);<br><br>        sb.append(event.getType());<br><br>        sb.append(&quot;, realmId=&quot;);<br><br>        sb.append(event.getRealmId());<br><br>        sb.append(&quot;, clientId=&quot;);<br><br>        sb.append(event.getClientId());<br><br>        sb.append(&quot;, userId=&quot;);<br><br>        sb.append(event.getUserId());<br><br>        sb.append(&quot;, ipAddress=&quot;);<br><br>        sb.append(event.getIpAddress());<br><br><br>//        if (event.getError() != null) {<br>//<br>//            sb.append(&quot;, error=&quot;);<br>//<br>//            sb.append(event.getError());<br>//<br>//        }<br><br><br>        if (event.getDetails() != null) {<br><br>            for (Entry&lt;String, String&gt; e : event.getDetails().entrySet()) {<br><br>                sb.append(&quot;, &quot;);<br><br>                sb.append(e.getKey());<br><br>                if (e.getValue() == null || e.getValue().indexOf(&#39; &#39;) == -1) {<br><br>                    sb.append(&quot;=&quot;);<br><br>                    sb.append(e.getValue());<br><br>                } else {<br><br>                    sb.append(&quot;=&#39;&quot;);<br><br>                    sb.append(e.getValue());<br><br>                    sb.append(&quot;&#39;&quot;);<br><br>                }<br><br>            }<br><br>        }<br><br><br>        return sb.toString();<br><br>    }<br><br> <br> private String toString(AdminEvent adminEvent) {<br><br>        StringBuilder sb = new StringBuilder();<br><br><br>        sb.append(&quot;operationType=&quot;);<br><br>        sb.append(adminEvent.getOperationType());<br><br>        sb.append(&quot;, realmId=&quot;);<br><br>        sb.append(adminEvent.getAuthDetails().getRealmId());<br><br>        sb.append(&quot;, clientId=&quot;);<br><br>        sb.append(adminEvent.getAuthDetails().getClientId());<br><br>        sb.append(&quot;, userId=&quot;);<br><br>        sb.append(adminEvent.getAuthDetails().getUserId());<br><br>        sb.append(&quot;, ipAddress=&quot;);<br><br>        sb.append(adminEvent.getAuthDetails().getIpAddress());<br><br>        sb.append(&quot;, resourcePath=&quot;);<br><br>        sb.append(adminEvent.getResourcePath());<br><br><br>        if (adminEvent.getError() != null) {<br><br>            sb.append(&quot;, error=&quot;);<br><br>            sb.append(adminEvent.getError());<br><br>        }<br><br><br>        return sb.toString();<br><br>    }<br><br>}</pre><p>Important things to note is that this class implements <a href="https://www.keycloak.org/docs-api/21.0.1/javadocs/org/keycloak/events/EventListenerProvider.html">EventListenerProvider</a> interface. This interface has two methods onEvent and onAdminEvent. OnAdminEvent is called every time an event in admin side happens and onEvent is called when some event happens on user side.</p><p>There are functions toString for admin and user to help display more information about the event. In onEvent I have added a if condition that is type of event is LOGIN which means that a user successfully logged in that display that event.</p><p>7. Create another file SampleEventListeneProviderFactory.java under the same folder as Provider.</p><pre>package com.keycloaktesting.sampleeventlistenerprovider.provider;<br><br>import org.keycloak.Config.Scope;<br>import org.keycloak.events.EventListenerProvider;<br>import org.keycloak.events.EventListenerProviderFactory;<br>import org.keycloak.models.KeycloakSession;<br>import org.keycloak.models.KeycloakSessionFactory;<br><br>public class SampleEventListenerProviderFactory implements EventListenerProviderFactory {<br><br> @Override<br> public EventListenerProvider create(KeycloakSession session) {<br>  return new SampleEventListenerProvider();<br> }<br><br> @Override<br> public void init(Scope config) {<br><br> }<br><br> @Override<br> public void postInit(KeycloakSessionFactory factory) {<br><br> }<br><br> @Override<br> public void close() {<br>  <br> }<br><br> @Override<br> public String getId() {<br>  return &quot;sample_event_listener&quot;;<br> }<br><br>}</pre><p>This factory just instiantes our Listener Provider object in create method. As given in Server Developer Guide for <a href="https://www.keycloak.org/docs/latest/server_development/#_implementing_spi">Implementing SPI</a> you need to defined a getId method which should return a unique id.</p><blockquote>It is recommended that your provider factory implementation returns unique id by method getId(). However there can be some exceptions to this rule as mentioned below in the <a href="https://www.keycloak.org/docs/latest/server_development/#_override_builtin_providers">Overriding providers</a> section.</blockquote><p>7. Next we need to create src/main/resources folder if it does not exist. Under src/main/resources create folders META-INF and under that services. Create a file named <strong>org.keycloak.events.EventListenerProviderFactory</strong></p><p>8. In the configuration file in step 7 add the following code. This should be the path of your provider factory which will in turn call your provider.</p><pre>com.keycloaktesting.sampleeventlistenerprovider.provider.SampleEventListenerProviderFactory</pre><p>9. You need to use maven to build and package your app so that you can get generated jars. First build the project if the project is not built. Next for packaging for me as I am using Eclipse I right click on pom.xml and click maven build. In goals add <strong>package. </strong>See the screenshot below. Press run. You should see a output in console in Eclipse that it has created jar files and build is successful.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/857/1*Or43XsBoFuAxEdn-jJNWXw.png" /><figcaption>Maven build and package.</figcaption></figure><p>10. Next go to your project in windows explorer, go to target folder and you should see 2 jar files at root levels named sample-event-listener.jar and sample-event-listener-sources.jar. You only need the first one.</p><p>You will need this jar while setting up keycloak. With this the provider part is done.</p><h3>Dockerized Keycloak Setup</h3><p>I am using Keycloak 25.0.1 at time of writing of this article. Instructions may vary if you are using a newer version of Keycloak. See documentation for changes. Next we need to setup keycloak in docker so we can deploy our provider in keycloak provider folder and activate it. The original <a href="https://medium.com/@adwaitthattey/building-an-event-listener-spi-plugin-for-keycloak-5bf9de1b0965">guide</a> mentions that you need to create keycloak by following guide below, create a realm, create a user under realm with password and deploy the jar.</p><p><a href="https://www.keycloak.org/guides#getting-started">Guides - Keycloak</a></p><p>The guide mentions that you need to do this:</p><blockquote>The deployment process is pretty straightforward. We need to copy the sample-event-listener.jar to $KEYCLOAK_DIR/standalone/deployments/ where $KEYCLOAK_DIR is the main KeyCloak directory (after unzipping)</blockquote><blockquote>KeyCloak supports hot-reloading. So as soon we copy the jar file, keycloak should reload and deploy the plugin. But just to be sure, let’s restart the Keycloak server.</blockquote><p>For me as I want to deploy keycloak in docker I had to go on a different route. In my previous article of using REST API in docker with Keycloak <a href="https://medium.com/@jawadrashid/how-to-use-rest-api-for-keycloak-admin-through-node-js-app-cfac0372eb4a#a179">https://medium.com/@jawadrashid/how-to-use-rest-api-for-keycloak-admin-through-node-js-app-cfac0372eb4a#a179</a> I used the guide by Keycloak here <a href="https://www.keycloak.org/getting-started/getting-started-docker">https://www.keycloak.org/getting-started/getting-started-docker</a> to setup Keycloak in docker.</p><p>The above guide does deploy Keycloak in docker but I needed to copy provider files jar to the providers folder in Keycloak so the above guide was not sufficient as it does not create a docker file and I wanted to use docker compose.</p><p>I used Keycloak guide here <a href="https://www.keycloak.org/server/containers">https://www.keycloak.org/server/containers</a> for a starting point but still there were some missing pieces. So I decided to use the article <a href="https://saurav-samantray.medium.com/dockerize-keycloak-21-with-a-custom-theme-b6f2acad03d5">https://saurav-samantray.medium.com/dockerize-keycloak-21-with-a-custom-theme-b6f2acad03d5</a> along with the above guide to dockerize the environment.</p><ol><li>Basically start off a new folder and create Dockerfile as given below:</li></ol><pre>FROM quay.io/keycloak/keycloak:latest as builder<br><br>ENV KC_DB=postgres<br><br>WORKDIR /opt/keycloak<br><br># for demonstration purposes only, please make sure to use proper certificates in production instead<br>RUN keytool -genkeypair -storepass password -storetype PKCS12 -keyalg RSA -keysize 2048 -dname &quot;CN=server&quot; -alias server -ext &quot;SAN:c=DNS:localhost,IP:127.0.0.1&quot; -keystore conf/server.keystore<br><br>RUN /opt/keycloak/bin/kc.sh build<br><br>FROM quay.io/keycloak/keycloak:latest<br>COPY --from=builder /opt/keycloak/ /opt/keycloak/<br><br>COPY --chown=keycloak:keycloak --chmod=644 ./providers/ /opt/keycloak/providers/<br><br>ENTRYPOINT [&quot;/opt/keycloak/bin/kc.sh&quot;]</pre><p>Here in this docker file we are using keycloak latest docker file as starting point and also we are copying the jar files in our providers folder to /opt/keycloak/providers/ directory under docker. The reason is that the guide mentions the following:</p><blockquote>To install custom providers, you just need to define a step to include the JAR file(s) into the /opt/keycloak/providers directory</blockquote><p>2. Create a providers directory in same folder that your dockerfile exists. Add the jar we created named sample-event-listener.jar to the providers folder so it can be copied into docker container.</p><p>3. Create an empty keycloak directory as well.</p><p>4. Create docker-compose.yaml at same level as Dockerfile. The contents are as below:</p><pre>version: &#39;3&#39;<br><br>volumes:<br>  keycloak-db-data:<br>    driver: local<br><br>services:<br>  postgres:<br>    image: postgres:13.7<br>    container_name: postgres<br>    volumes:<br>      - keycloak-db-data:/var/lib/postgresql/data<br>    environment:<br>      POSTGRES_DB: keycloak<br>      POSTGRES_USER: keycloak_admin<br>      POSTGRES_PASSWORD: keycloak_password<br>  keycloak:<br>    build: .<br>    container_name: custom-auth-service<br>    environment:<br>      #Admin Credentials<br>      KC_HOSTNAME_STRICT: &#39;false&#39;<br>      KC_HOSTNAME_STRICT_HTTPS: &#39;false&#39;<br>      KEYCLOAK_ADMIN: admin<br>      KEYCLOAK_ADMIN_PASSWORD: admin<br>      KEYCLOAK_USER: admin<br>      KEYCLOAK_PASSWORD: admin<br>      KC_DB_URL_HOST: postgres<br>      KC_DB_USERNAME: keycloak_admin<br>      KC_DB_PASSWORD: keycloak_password<br>      KC_HEALTH_ENABLED: &#39;true&#39;<br>      KC_METRICS_ENABLED: &#39;true&#39;<br>      KC_HOSTNAME: localhost<br>      PROXY_ADDRESS_FORWARDING: &quot;true&quot;<br>    command:<br>      - &quot;start-dev&quot;<br>    ports:<br>      - 8443:8443<br>      - 8080:8080<br>    depends_on:<br>      - postgres</pre><p>We will deploy a main container with keycloak named custom-auth-service and another container for postgresql as we are using postgresql for database. You can customize postgresql settings in yaml file above. One thing to note is that we are executing command start-dev as we want to start the server in development mode.</p><p>5. Use the following command to build and run keycloak with database in docker.</p><pre>docker-compose up --build</pre><p>6. When Keycloak runs in docker. You might see message as below that it has detected eventsListener.</p><pre>sample_event_listener (com.keycloaktesting.sampleeventlistenerprovider.provider.SampleEventListenerProviderFactory) is implementing the internal SPI eventsListener. This SPI is internal and may change without notice</pre><p>7. You need to create a realm, create a user and set password by following the guide: <a href="https://www.keycloak.org/getting-started/getting-started-docker">https://www.keycloak.org/getting-started/getting-started-docker</a></p><p>8. Once you have done all the steps in guide in step 7 then go to <a href="http://localhost:8080/admin/">http://localhost:8080/admin/</a> login through your keycloak admin. Select your custom realm from dropdown on top left. For me my realm was myrealm.</p><p>9. Go to events page under manage section in sidebar</p><p>10. Click on <strong>Event configs </strong>link in the paragraph in events page. You can go directly to this url <a href="http://localhost:8080/admin/master/console/#/myrealm/realm-settings/events">http://localhost:8080/admin/master/console/#/myrealm/realm-settings/events</a> replacing myrealm with your realm name in url.</p><p>11. In events listener start typing sample and in event listeners and select sample_event_listener. This is the event listener we created by implementing SPI.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*YSU7HfGPB68_NB44oAkPDw.png" /><figcaption>Add sample_event_listener in event listeners.</figcaption></figure><p>12. Now open up your docker container custom-auth-service logs section.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/586/1*ejpcTTWbV4_hzK-fQz6E-w.png" /><figcaption>Logs under custom-auth-service</figcaption></figure><p>13. Clear your docker logs by clicking on delete button in logs section on right so you will be able to see the message you created on login clearly.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/267/1*qtNUhAuOL4o4uDxg8gtEdw.png" /></figure><p>14. Open up <a href="http://localhost:8080/realms/myrealm/account">http://localhost:8080/realms/myrealm/account</a> where myrealm is your realm name and login with the user you created while creating keycloak guide in step 7.</p><p>15. Go back to logs under docker and you should see message as below. This message was generated by our SPI code. As I have set up a condition that only LOGIN event should be displayed you will see only LOGIN event. This message means that our code is working and Keycloak is using our provider.</p><pre>Event Occurred:Event FOUND, type=LOGIN, <br>realmId=560a9b9d-2917-..., <br>clientId=account-console, <br>userId=13af8b9e-fa44-..., <br>ipAddress=192.168...., <br>auth_method=openid-connect, <br>auth_type=code, <br>redirect_uri=http://localhost:8080/realms/myrealm/account, <br>consent=no_consent_required, <br>code_id=5cb473a8-35c8-..., <br>username=myuser</pre><p>All the code is available at <a href="https://github.com/jawadrashid2011/keycloak-spi-eventlistener">https://github.com/jawadrashid2011/keycloak-spi-eventlistener</a>. Look in resources section for further guides from where I have taken code from. Want to read something else read my last article here: <a href="https://medium.com/@jawadrashid/how-to-use-rest-api-for-keycloak-admin-through-node-js-app-cfac0372eb4a#a179">How to use REST API for Keycloak Admin Through Node JS App</a></p><h3>Resources</h3><ul><li>Final github code: <a href="https://github.com/jawadrashid2011/keycloak-spi-eventlistener">https://github.com/jawadrashid2011/keycloak-spi-eventlistener</a></li><li><a href="https://medium.com/@adwaitthattey/building-an-event-listener-spi-plugin-for-keycloak-5bf9de1b0965">Building an Event Listener SPI (Plugin) for KeyCloak</a> by Adwait Thattey. Most of the code is taken from this article and modified slightly to meet needs.</li><li><a href="https://www.youtube.com/playlist?list=PLQZfys2xO5kgpa9-qpJly78d-t7_Fnjec">Keycloak and Docker by code215</a> gives docker configuration and video 7 discusses how to implement event listener SPI. It is a great series.</li><li><a href="https://medium.com/@jawadrashid/how-to-use-rest-api-for-keycloak-admin-through-node-js-app-cfac0372eb4a#a179">How to use REST API for Keycloak Admin Through Node JS App </a>— My last article on how to use REST API with Keycloak in Postman and Node JS</li><li>Keycloak Server Guide for implementing SPI <a href="https://www.keycloak.org/docs/latest/server_development/#_providers">https://www.keycloak.org/docs/latest/server_development/#_providers</a></li><li><a href="https://www.keycloak.org/docs-api/21.0.1/javadocs/org/keycloak/events/EventListenerProvider.html">EventsListenerProvider</a>, <a href="https://www.keycloak.org/docs-api/21.0.1/javadocs/org/keycloak/events/EventListenerProviderFactory.html">EventListenerProviderFactory</a></li><li>Keycloak setup <a href="https://www.keycloak.org/guides#getting-started">https://www.keycloak.org/guides#getting-started</a></li><li>Keycloak dockerization setup without containers <a href="https://www.keycloak.org/getting-started/getting-started-docker">https://www.keycloak.org/getting-started/getting-started-docker</a></li><li>Keycloak docker with containers <a href="https://www.keycloak.org/server/containers">https://www.keycloak.org/server/containers</a></li><li>Guide on how to dockerize Keycloak through container and modify themes <a href="https://saurav-samantray.medium.com/dockerize-keycloak-21-with-a-custom-theme-b6f2acad03d5">https://saurav-samantray.medium.com/dockerize-keycloak-21-with-a-custom-theme-b6f2acad03d5</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1f01ae819e8d" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to use REST API for Keycloak Admin Through Node JS App]]></title>
            <link>https://medium.com/@jawadrashid/how-to-use-rest-api-for-keycloak-admin-through-node-js-app-cfac0372eb4a?source=rss-c13478e3b633------2</link>
            <guid isPermaLink="false">https://medium.com/p/cfac0372eb4a</guid>
            <category><![CDATA[postman]]></category>
            <category><![CDATA[docker]]></category>
            <category><![CDATA[keycloak]]></category>
            <category><![CDATA[nodejs]]></category>
            <category><![CDATA[rest-api]]></category>
            <dc:creator><![CDATA[Jawad Rashid]]></dc:creator>
            <pubDate>Sun, 07 Jul 2024 12:58:55 GMT</pubDate>
            <atom:updated>2024-07-07T12:58:55.788Z</atom:updated>
            <content:encoded><![CDATA[<p>Keycloak allows you to add authentication to your applications and services with ease. Keycloak defines its software as:</p><blockquote>Keycloak provides user federation, strong authentication, user management, fine-grained authorization, and more.</blockquote><h3>Table Of Contents</h3><ul><li><a href="#e372">Introduction</a></li><li><a href="#a179">Keycloak Setup</a></li><li><a href="#b9ac">Postman Example</a></li><li><a href="#9487">Node.js Keycloak Admin Application</a></li><li><a href="#2424">Final Code</a></li><li><a href="#0d96">Resources</a></li></ul><h3>Introduction</h3><p>In this article I will give an example on how to use REST api for KeyCloak admin.</p><p>First example I will use will be using <a href="https://www.postman.com/">Postman</a> application to log in to Keycloak admin section and perform a GET action on one of the resources available through Keycloak admin.</p><p>In next example, I will share code for a Node application on how to authenticate through Keycloak admin client library and get information on users registered with Keycloak.</p><p>I will modify the example in the end to showcase how to logout a logged in user to Keycloak using Node.js Admin library. It will be an extension of the last example.</p><h3><strong>Keycloak Setup</strong></h3><p>In order to test out the REST api for Keycloak admin we need to first have Keycloak server running. For this article I will setup Keycloak in docker. You can follow along by using the guide here (<a href="https://www.keycloak.org/getting-started/getting-started-docker">https://www.keycloak.org/getting-started/getting-started-docker</a>). I am just going to repeat the main steps.</p><ol><li>Install Keycloak under Keycloak by running the following command. Here we running development server of Keycloak with standard options with latest version which at the time of writing was 25.0.1. You can explore keycloak documentation for customization.</li></ol><pre>docker run -p 8080:8080 -e KEYCLOAK_ADMIN=admin -e KEYCLOAK_ADMIN_PASSWORD=admin quay.io/keycloak/keycloak:25.0.1 start-dev</pre><p>2. Login to Keycloak Admin Console at <a href="http://localhost:8080/admin">http://localhost:8080/admin</a> with your username and password in first step which in our case is admin/admin</p><p>3. Create realm and user by following the guide I gave here <a href="https://www.keycloak.org/getting-started/getting-started-docker">https://www.keycloak.org/getting-started/getting-started-docker</a></p><p>4. Login to the user added by going to <a href="http://localhost:8080/realms/myrealm/account">http://localhost:8080/realms/myrealm/account</a></p><p>5. Follow the guide and follow the section titled “Secure the first application”</p><p>With keycloak up and running we can switch to Postman.</p><h3><strong>Postman Example</strong></h3><p>You can find Keycloak Admin REST api documentation here <a href="https://www.keycloak.org/docs-api/latest/rest-api/index.html">https://www.keycloak.org/docs-api/latest/rest-api/index.html</a></p><p>I might have missed something but I was not able to find clear instructions on Keycloak REST admin documentation on how to get a access token as all REST actions require a access token. This video <a href="https://www.youtube.com/watch?v=Xmjlcbt2LGE">https://www.youtube.com/watch?v=Xmjlcbt2LGE</a> helped me understand on how to get access token.</p><p>I will be using Postman to test REST api. The instructions on how to get access token are:</p><ol><li>Create a new request in Postman</li><li>Set the REST method as <strong>POST</strong></li><li>For url set it to <a href="http://localhost:8080/realms/master/protocol/openid-connect/token">http://localhost:8080/realms/master/protocol/openid-connect/token</a></li><li>Go into body section of the request, select x-www-form-urlencoded as body type and add the following key value pairs:</li></ol><ul><li><strong>key</strong>: username, <strong>value</strong>: admin<br>This is your keycloak admin username</li><li><strong>key: </strong>password, <strong>value: </strong>admin<br>Your keycloak admin password</li><li><strong>key: </strong>client_id, <strong>value: </strong>admin-cli</li><li><strong>key: </strong>grant_type, <strong>value: </strong>password</li></ul><p>5. Here is a screenshot of the request in Postman</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*wxCvT7EELbqTCapK_EqtIQ.png" /><figcaption>These are all the options I described for authentication in Step 3 and Step 4</figcaption></figure><p>6. Click Send and in response you will get a json with access_token.</p><p>7. As we will need to use this access_token in multiple requests and it expires in a minute. We can either increase the access_token expiry time or use Postman collection variables. Here I choose to use collection variables.</p><p>8. In order to use collection variable make sure that you create a collection for your project in Postman and save your Authenticate request which I described above in that collection. You can save a request in collection by using save button on top send button. In my case I saved it under a collection named “<strong>Keycloak</strong>”</p><p>9. You can use collection variables by setting them in a request and using these variables in other requests within another request.</p><p>10. I will save the access_token in Postman variable named BEARER_TOKEN. Just go to the tests tab in your Authentication tab, and paste in the following code which sets the collection variable BEARER_TOKEN with the access_token received.</p><pre>pm.test(&quot;response is ok&quot;,  ()=&gt;{<br>    pm.response.to.have.status(200)<br>})<br><br>var jsonData = JSON.parse(responseBody);<br><br>pm.collectionVariables.set(&quot;BEARER_TOKEN&quot;, jsonData.access_token);</pre><p>11. Whenever you run the authenticate request in Postman the test given above will run and save the access_token returned in BEARER_TOKEN collection variable.</p><p>Now, let’s test some REST actions by looking through the Keycloak REST admin api documentation.</p><ol><li>We can look up in documentation that we can get sessions stats for a realm i.e. if there are any logged in users. The documentation for the above action is given below in screenshot taken from Keycloak docs.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*pOkbqMUKT4asje3miaiMYw.png" /><figcaption>Client Sessions Stats Documentation</figcaption></figure><p>2. As we can see from the docs that you need to select a realm in the url and it will return stats. Let’s set up a new request for this.</p><p>3. Add a new request in the Postman collection for the project (in my case it is named <strong>Keycloak</strong>).</p><p>4. Select REST method as GET</p><p>5. Set url as <a href="http://localhost:8080/admin/realms/myrealm/client-session-stats">http://localhost:8080/admin/realms/myrealm/client-session-stats</a> (change myrealm in url with the name of your realm you created while setting up Keycloak)</p><p>6. This will not work without the access token so go to the authorization tab in your new request.</p><p>7. From the dropdown for type of authorization select <strong>Bearer Token</strong></p><p>8. In the Token field add <strong>{{BEARER_TOKEN}} </strong>where BEARER_TOKEN is the collection variable we set in authentication request.</p><p>9. First login a user you created while setting up Docker my going to the url: <a href="http://localhost:8080/realms/myrealm/account">http://localhost:8080/realms/myrealm/account</a> and giving username and password for user you created.</p><p>10. Now go back to Postman. First run authenticate request in Postman which will set the BEARER_TOKEN with access_token.</p><p>11. Now run the client stats request and it will give you an output like below:</p><pre>[<br>    {<br>        &quot;offline&quot;: &quot;0&quot;,<br>        &quot;clientId&quot;: &quot;account-console&quot;,<br>        &quot;active&quot;: &quot;1&quot;,<br>        &quot;id&quot;: &quot;7e8bc9f6-42ac-4265-90f9-ca9219cb484a&quot;<br>    }<br>]</pre><p>12. As we have logged in 1 user this shows us that 1 user is logged in and the id of the user.</p><p>We can do this again for listing more details for users for a realm by making a request at <a href="http://localhost:8080/admin/realms/myrealm/users">http://localhost:8080/admin/realms/myrealm/users</a> and it will give a response like below. I got the url by going through Keycloak REST docs.</p><pre>[<br>    {<br>        &quot;id&quot;: &quot;e4c5893b-ce6f-4880-91e0-c68df109480f&quot;,<br>        &quot;username&quot;: &quot;myuser&quot;,<br>        &quot;firstName&quot;: &quot;Developer&quot;,<br>        &quot;lastName&quot;: &quot;Man&quot;,<br>        &quot;email&quot;: &quot;test@test.com&quot;,<br>        &quot;emailVerified&quot;: false,<br>        &quot;createdTimestamp&quot;: 1719925905091,<br>        &quot;enabled&quot;: true,<br>        &quot;totp&quot;: false,<br>        &quot;disableableCredentialTypes&quot;: [],<br>        &quot;requiredActions&quot;: [],<br>        &quot;notBefore&quot;: 1719929615,<br>        &quot;access&quot;: {<br>            &quot;manageGroupMembership&quot;: true,<br>            &quot;view&quot;: true,<br>            &quot;mapRoles&quot;: true,<br>            &quot;impersonate&quot;: true,<br>            &quot;manage&quot;: true<br>        }<br>    }<br>]</pre><p>You can use this for more actions which are user specific. This the end of the Postman section of using Keycloak. Let’s switch to creating a node application for keycloak REST admin api.</p><h3><strong>Node.js Keycloak Admin Application</strong></h3><p>The Node.js application we will create will retrieve all logged in users and terminate session for a single user so they get logged out. Here are the steps:</p><ol><li>Searching for Keycloak Admin Node client library I found that there is a node js package <a href="https://www.npmjs.com/package/keycloak-connect">https://www.npmjs.com/package/keycloak-connect</a> which helps us to connect to Keycloak Admin.</li><li>I will be using the documentation given on their github repo here: <a href="https://github.com/keycloak/keycloak/tree/main/js/libs/keycloak-admin-client">https://github.com/keycloak/keycloak/tree/main/js/libs/keycloak-admin-client</a></li><li>First select a folder for your node js application and run the following command to install Node JS Keycloak admin client library:</li></ol><pre>npm install @keycloak/keycloak-admin-client</pre><p>4. Now create app.js in your project.</p><p>5. Import Admin client library on top of your node app</p><pre>import KcAdminClient from &#39;@keycloak/keycloak-admin-client&#39;;</pre><p>6. The doc states that you can connect to keycloak by using the following code:</p><pre>// To configure the client, pass an object to override any of these  options:<br>// {<br>//   baseUrl: &#39;http://127.0.0.1:8080&#39;,<br>//   realmName: &#39;master&#39;,<br>//   requestOptions: {<br>//     /* Fetch request options https://developer.mozilla.org/en-US/docs/Web/API/fetch#options */<br>//   },<br>// }<br>const kcAdminClient = new KcAdminClient();</pre><p>7. In my case I wanted to use localhost instead of 127.0.0.1 as it was not working so I customized the admin library by changing the above code to following code. You can customize more options by looking up available options.</p><pre>const kcAdminClient = new KcAdminClient({<br>    baseUrl: &#39;http://localhost:8080&#39;<br>}<br>);</pre><p>8. Next authenticate to keycloak admin by using the code below. These are all the same options we added while authenticating through Postman.</p><pre>await kcAdminClient.auth({<br>    username: &#39;admin&#39;,<br>    password: &#39;admin&#39;,<br>    grantType: &#39;admin-cli&#39;,<br>    clientId: &#39;myrealm&#39;<br>  });</pre><p>9. You can set a default realm for further requests which we will do.</p><pre>  kcAdminClient.setConfig({<br>    realmName: &#39;myrealm&#39;,<br>  });</pre><p>10. Let’s just get a list of all clients by following one of the examples in the documentation</p><pre>  const users = await kcAdminClient.users.find({ first: 0, max: 10 });<br>  console.log(users);</pre><p>11. You will get a response like below which is same response you got using Postman.</p><pre>[<br>  {<br>    id: &#39;e4c5893b-ce6f-4880-91e0-c68df109480f&#39;,<br>    username: &#39;myuser&#39;,<br>    firstName: &#39;Developer&#39;,<br>    lastName: &#39;Man&#39;,<br>    email: &#39;test@test.com&#39;,<br>    emailVerified: false,<br>    createdTimestamp: 1719925905091,<br>    enabled: true,<br>    totp: false,<br>    disableableCredentialTypes: [],<br>    requiredActions: [],<br>    notBefore: 1719929615,<br>    access: {<br>      manageGroupMembership: true,<br>      view: true,<br>      mapRoles: true,<br>      impersonate: true,<br>      manage: true<br>    }<br>  }<br>]</pre><p>12. Remove the code defined in step 10 for users.find and console.log. Let’s find all logged in users. Looking through the node.js client library and also Keycloak documentation I found out that we can find all logged in users but first we need the client id. In order to do that we will use the following code:</p><pre>const clients = await kcAdminClient.clients.find({clientId: &#39;account-console&#39;});</pre><p>13. Here account-console is the value we need. I found all client id in our app by running a Postman request at <a href="http://localhost:8080/admin/realms/myrealm/clients">http://localhost:8080/admin/realms/myrealm/clients</a>. The response included values of account, account-console, admin-cli, broker, myclient, realm-management, and security-admin-console.</p><p>14. After looking at docs I found out that account-console is the value we need to find client id for users.</p><p>15. In next step we will list all sessions for users that are logged in. I created two more users by going into <a href="http://localhost:8080/admin">http://localhost:8080/admin</a> and creating users. Choose your custom realm <strong>myrealm </strong>(in my case) before creating users.</p><p>16. Log in another user in another browser created in step 15 so you have more than 1 logged in user.</p><p>17. List all logged in users by running the code below. Here this functions needs id which is the client id we found om step 12.</p><pre>const logged_in_users = await kcAdminClient.clients.listSessions({id: clients[0][&#39;id&#39;]});</pre><p>18. Last step is that if there is any logged in user then select 1 user and log them out. Run the following code:</p><pre>if(logged_in_users.length &gt; 0) {<br>    console.log(&quot;Logged out &quot;, logged_in_users[0][&#39;id&#39;], logged_in_users[0][&#39;username&#39;], logged_in_users[0][&#39;userId&#39;])<br>    const response = await kcAdminClient.realms.removeSession({ realm: KEYCLOAK_REALM,sessionId: logged_in_users[0][&#39;id&#39;]});<br>}</pre><p>19. Now run the app and you will see the username of the user that was logged out. Just go to that user browser tab and refresh and you will see that you are logged out. Go to the other user session and refresh and they should be logged in. This means that our code is running.</p><p>By looking at the code in github docs for Node.JS client library and Keycloak admin REST api documentation you can find how to perform actions and what are the required values for that. Hope you found this article useful. I am posting the final code below along with any resources.</p><h3>Final Code</h3><p>I added some code to use values from environment variables if you want to use it.</p><pre>import KcAdminClient from &#39;@keycloak/keycloak-admin-client&#39;;<br><br>/* Setting Environment and defaults */<br>const BASE_URL =                process.env.BASE_URL                || &#39;http://localhost:8080&#39;;<br>const KEYCLOAK_USERNAME =       process.env.KEYCLOAK_USERNAME       || &#39;admin&#39;;<br>const KEYCLOAK_PASSWORD =       process.env.KEYCLOAK_PASSWORD       || &#39;admin&#39;;<br>const KEYCLOAK_GRANT_TYPE =     process.env.KEYCLOAK_GRANT_TYPE     || &#39;password&#39;;<br>const KEYCLOAK_CLIENT_ID =      process.env.KEYCLOAK_CLIENT_ID      || &#39;admin-cli&#39;;<br>const KEYCLOAK_REALM =          process.env.KEYCLOAK_REALM          || &#39;myrealm&#39;;<br><br>const kcAdminClient = new KcAdminClient({<br>    baseUrl: BASE_URL<br>}<br>);<br><br>await kcAdminClient.auth({<br>    username: KEYCLOAK_USERNAME,<br>    password: KEYCLOAK_PASSWORD,<br>    grantType: KEYCLOAK_GRANT_TYPE,<br>    clientId: KEYCLOAK_CLIENT_ID<br>  });<br>  <br>  // List first page of users<br>  kcAdminClient.setConfig({<br>    realmName: KEYCLOAK_REALM,<br>  });<br><br>// Find the client id for users. For me following the guide the users created in custom realm had clientId. <br>// Standard Client Id in dev server below are account, account-console, admin-cli, broker, myclient, realm-management,<br>// security-admin-console<br><br>// This is to get the client id to be used below<br>const clients = await kcAdminClient.clients.find({clientId: &#39;account-console&#39;});<br><br>// Findings all logged in users for account-console. <br>const logged_in_users = await kcAdminClient.clients.listSessions({id: clients[0][&#39;id&#39;]});<br>// console.log(logged_in_users);<br><br>if(logged_in_users.length &gt; 0) {<br>    console.log(&quot;Logged out &quot;, logged_in_users[0][&#39;id&#39;], logged_in_users[0][&#39;username&#39;], logged_in_users[0][&#39;userId&#39;])<br>    const response = await kcAdminClient.realms.removeSession({ realm: KEYCLOAK_REALM,sessionId: logged_in_users[0][&#39;id&#39;]});<br>}</pre><p>Package.json</p><pre>{<br>  &quot;type&quot;: &quot;module&quot;,<br>  &quot;dependencies&quot;: {<br>    &quot;@keycloak/keycloak-admin-client&quot;: &quot;^25.0.1&quot;<br>  }<br>}</pre><h3>Resources</h3><ol><li>Keycloak Docker Setup: <a href="https://www.keycloak.org/getting-started/getting-started-docker">https://www.keycloak.org/getting-started/getting-started-docker</a></li><li>Keycloak admin console url: <a href="http://localhost:8080/admin">http://localhost:8080/admin</a></li><li>Keycloak user login: <a href="http://localhost:8080/realms/myrealm/account">http://localhost:8080/realms/myrealm/account</a></li><li>Keycloak REST admin API documentation: <a href="https://www.keycloak.org/docs-api/latest/rest-api/index.html">https://www.keycloak.org/docs-api/latest/rest-api/index.html</a></li><li>YouTube video on how to use Keycloak REST api in Postman: <a href="https://www.youtube.com/watch?v=Xmjlcbt2LGE">https://www.youtube.com/watch?v=Xmjlcbt2LGE</a></li><li>Keycloak Node.JS admin client library package: <a href="https://www.npmjs.com/package/keycloak-connect">https://www.npmjs.com/package/keycloak-connect</a></li><li>Keycloak Node.JS admin client library github documentation with examples: <a href="https://github.com/keycloak/keycloak/tree/main/js/libs/keycloak-admin-client">https://github.com/keycloak/keycloak/tree/main/js/libs/keycloak-admin-client</a></li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=cfac0372eb4a" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>