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
-
docker-compose.yml:
-
This file contains the configuration to run a Keycloak container.
-
Make sure the
docker-compose.yml
file is set up as provided in your project. -
realm-export.json:
- This file should be configured according to your Keycloak realm requirements.
- It contains realm, client, user, and role configurations.
Step 2: Setting Up Node.js Application
-
package.json:
-
This file contains your project metadata and dependencies.
-
Ensure
express
,express-session
, andkeycloak-connect
dependencies are listed. -
index.js:
-
This file contains your Express application setup.
-
It sets up routes for login, logout, and the home page which displays the JWT.
-
keycloak.json:
-
This file contains the Keycloak client configuration.
-
Update the
realm
,resource
, andcredentials
fields with your Keycloak configuration. -
Installing Dependencies:
- Run the following command to install the necessary packages as listed in your
package.json
:
npm i
Step 3: Running the Services
-
Linux/macOS:
-
Ensure
run.sh
is executable:chmod +x run.sh
. -
Execute
run.sh
to start the services:./run.sh
. -
Windows:
- Double-click
run.bat
or run it in the command prompt to start the services.
Accessing the Application
- Navigate to
localhost:3000/auth
to log in using Keycloak. - Once logged in, navigate to
localhost:3000
to view the JWT and its decoded payload. - To logout, navigate to
localhost:3000/logout
.
Step 1: Install and Setup Keycloak
- Download and install Keycloak from the official website.
- Start Keycloak by navigating to the
bin
directory of your Keycloak installation and executing thestandalone.sh
(for Linux/macOS) orstandalone.bat
(for Windows) script. - 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)
-
Create a New Realm:
-
Navigate to the Keycloak Admin Console.
- Click on "Add realm" to create a new realm.
-
Enter the required details for your realm and save.
-
Register a Client:
-
Navigate to
Clients
and clickCreate
. - Provide a
Client ID
, and select theClient Protocol
asopenid-connect
. - Select the
Client Access Type
asconfidential
if your client is a web application that can secure the client secret. Otherwise, selectpublic
if your client is a native app or a JavaScript app running in the browser. -
Set
Standard Flow Enabled
toON
if you want to use the Authorization Code Flow which is recommended for most scenarios. -
Configure OpenID Connect Protocol:
-
For each client, you can tailor what claims and assertions are stored in the OIDC token by creating and configuring protocol mappers.
-
You may need to set up JSON mapping for certain claim keys in your application to handle roles or other claims passed by Keycloak.
-
Client Adapters:
-
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.
-
Test Your Setup:
-
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.
-
Additional Configuration (Optional):
-
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.
-
Documentations and Tutorials:
- 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
- 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
- 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
- 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
- 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
-
docker-compose.yml:
-
This file contains the configuration to run a Keycloak container.
-
Ensure it's set up as provided in your project.
-
realm-export.json:
- Configure this file according to your Keycloak realm requirements.
- It contains realm, client, user, and role configurations.
Step 2: Setting Up Python Flask Application
-
requirements.txt:
-
Lists the necessary Python packages, including Flask and Flask-OIDC.
-
client_secrets.json:
-
Contains Keycloak client configuration.
-
Update the
client_id
,client_secret
, and URLs according to your Keycloak setup. -
index.py:
- Contains your Flask application.
- 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
-
Linux/macOS:
-
Make
run.sh
executable:chmod +x run.sh
. -
Execute
run.sh
to start the services:./run.sh
. -
Windows:
- Execute
run.bat
to start the services.
Accessing the Application
- Navigate to
https://localhost:3000/
(accept the self-signed certificate warning). - Use the Keycloak authentication process to log in.
- Once logged in, user information will be displayed on the home page.
- To logout, navigate to
https://localhost:3000/logout
.
Important Notes
- Ensure all URLs in
client_secrets.json
andrealm-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