Examples

This section includes examples in different programming languages on how integration with the provided KeyCloak can be performed.

Nodejs

Prerequisites

  • Docker and Docker Compose installed.
  • Node.js and npm installed.
  • Basic understanding of Keycloak, Docker, and Node.js.

Project Structure

Source: example

example/
|-- docker-compose.yml
|-- realm-export.json
|-- keycloak.json
|-- package.json
|-- index.js
|-- run.sh         (for Linux/macOS)
|-- run.bat        (for Windows)

Step 1: Setting Up Keycloak

  1. docker-compose.yml:

  2. This file contains the configuration to run a Keycloak container.

  3. Make sure the docker-compose.yml file is set up as provided in your project.

  4. realm-export.json:

  5. This file should be configured according to your Keycloak realm requirements.
  6. It contains realm, client, user, and role configurations.

Step 2: Setting Up Node.js Application

  1. package.json:

  2. This file contains your project metadata and dependencies.

  3. Ensure express, express-session, and keycloak-connect dependencies are listed.

  4. index.js:

  5. This file contains your Express application setup.

  6. It sets up routes for login, logout, and the home page which displays the JWT.

  7. keycloak.json:

  8. This file contains the Keycloak client configuration.

  9. Update the realm, resource, and credentials fields with your Keycloak configuration.

  10. Installing Dependencies:

  11. Run the following command to install the necessary packages as listed in your package.json:
npm i

Step 3: Running the Services

  1. Linux/macOS:

  2. Ensure run.sh is executable: chmod +x run.sh.

  3. Execute run.sh to start the services: ./run.sh.

  4. Windows:

  5. Double-click run.bat or run it in the command prompt to start the services.

Accessing the Application

  1. Navigate to localhost:3000/auth to log in using Keycloak.
  2. Once logged in, navigate to localhost:3000 to view the JWT and its decoded payload.
  3. To logout, navigate to localhost:3000/logout.

Step 1: Install and Setup Keycloak

  1. Download and install Keycloak from the official website.
  2. Start Keycloak by navigating to the bin directory of your Keycloak installation and executing the standalone.sh (for Linux/macOS) or standalone.bat (for Windows) script.
  3. Access the Keycloak Admin Console at http://localhost:8080/auth and complete the initial setup. Create an admin user for managing Keycloak.

Step 2: Create a Realm and a Client (OpenID Connect)

  1. Create a New Realm:

  2. Navigate to the Keycloak Admin Console.

  3. Click on "Add realm" to create a new realm.
  4. Enter the required details for your realm and save.

  5. Register a Client:

  6. Navigate to Clients and click Create.

  7. Provide a Client ID, and select the Client Protocol as openid-connect.
  8. Select the Client Access Type as confidential if your client is a web application that can secure the client secret. Otherwise, select public if your client is a native app or a JavaScript app running in the browser.
  9. Set Standard Flow Enabled to ON if you want to use the Authorization Code Flow which is recommended for most scenarios.

  10. Configure OpenID Connect Protocol:

  11. For each client, you can tailor what claims and assertions are stored in the OIDC token by creating and configuring protocol mappers.

  12. You may need to set up JSON mapping for certain claim keys in your application to handle roles or other claims passed by Keycloak.

  13. Client Adapters:

  14. Install a Keycloak Adapter in your application environment to communicate and be secured by Keycloak. Keycloak provides adapters for different platforms, and there are also third-party adapters available.

  15. Test Your Setup:

  16. At this point, it would be prudent to test your setup by attempting to authenticate using OpenID Connect. There are various grant types supported by Keycloak for authenticating users including authorization code, implicit, and client credentials.

  17. Additional Configuration (Optional):

  18. Depending on your application's requirements, you might need to configure additional settings in Keycloak or in your application. For instance, you might need to set up user roles, groups, and permissions, or configure multi-factor authentication.

  19. Documentations and Tutorials:

  20. There are various resources available that provide step-by-step guides or tutorials on integrating OpenID Connect with Keycloak, including the Keycloak official documentation.

This extended step should provide a more thorough understanding of how to integrate OpenID Connect with Keycloak. However, the exact steps might vary based on your application's technology stack and your specific requirements.

Step 3: Configure your System

  1. For a JavaScript application, you could use the Keycloak JavaScript adapter.
npm install keycloak-js

or a middleware as keycloak-connect

npm install keycloak-connect
  1. Configure the library with the details of your Keycloak realm and client.
// Example configuration for a JavaScript application
const keycloak = Keycloak({
  url: "http://localhost:8080/auth",
  realm: "<your-realm>",
  clientId: "<your-client-id>",
});

Step 4: Integrate Authentication

  1. Use the library to add authentication to your system. For a web application, this would typically involve redirecting unauthenticated users to the Keycloak login page, and handling the tokens returned by Keycloak upon successful authentication.
// Example integration for a JavaScript application
keycloak
  .init({ onLoad: "login-required" })
  .then((authenticated) => {
    console.log(authenticated ? "Authenticated" : "Not authenticated");
  })
  .catch((error) => {
    console.error("Failed to initialize authentication", error);
  });

Step 5: Integrate Authorization

  1. Use the tokens obtained during authentication to make authorized requests to your system's backend, and to check the user's roles and permissions.
// Example authorization check in a JavaScript application
if (keycloak.hasRealmRole("admin")) {
  console.log("User is an admin");
}

This tutorial provides a high-level overview of the steps involved in integrating Keycloak with your system. The exact steps and code may vary depending on the specifics of your system and the programming languages and frameworks you are using.


Python

Prerequisites

  • Docker and Docker Compose installed.
  • Python and pip installed.
  • Basic understanding of Keycloak, Docker, Flask, and Python.
  • Access the application over HTTPS and accept the self-signed certificate warning: "The certificate is not trusted because it is self-signed."

Project Structure

Source: example

example/
|-- docker-compose.yml
|-- realm-export.json
|-- client_secrets.json
|-- requirements.txt
|-- index.py
|-- run.sh         (for Linux/macOS)
|-- run.bat        (for Windows)

Step 1: Setting Up Keycloak

  1. docker-compose.yml:

  2. This file contains the configuration to run a Keycloak container.

  3. Ensure it's set up as provided in your project.

  4. realm-export.json:

  5. Configure this file according to your Keycloak realm requirements.
  6. It contains realm, client, user, and role configurations.

Step 2: Setting Up Python Flask Application

  1. requirements.txt:

  2. Lists the necessary Python packages, including Flask and Flask-OIDC.

  3. client_secrets.json:

  4. Contains Keycloak client configuration.

  5. Update the client_id, client_secret, and URLs according to your Keycloak setup.

  6. index.py:

  7. Contains your Flask application.
  8. Sets up routes for login, logout, and home page displaying user information.

Step 3: Installing Dependencies

  • Run the following command to install necessary Python packages:
pip install -r requirements.txt

Step 4: Running the Services

  1. Linux/macOS:

  2. Make run.sh executable: chmod +x run.sh.

  3. Execute run.sh to start the services: ./run.sh.

  4. Windows:

  5. Execute run.bat to start the services.

Accessing the Application

  1. Navigate to https://localhost:3000/ (accept the self-signed certificate warning).
  2. Use the Keycloak authentication process to log in.
  3. Once logged in, user information will be displayed on the home page.
  4. To logout, navigate to https://localhost:3000/logout.

Important Notes

  • Ensure all URLs in client_secrets.json and realm-export.json match your Keycloak configuration.
  • Remember to access the application via HTTPS and accept the browser warning about the self-signed certificate.
  • Modify the index.py file to suit your application's specific Flask and OIDC needs.

For more information you can visit the official documentation in https://www.keycloak.org/documentation