# How to Connect

# Connecting with Node.js

This guide explains how to establish a secure connection between a Node.js application and a Keycloak identity provider using the <span class="s2">keycloak-connect</span> middleware. It walks through the necessary setup, configuration, and usage of a protected route that requires authentication.

## **Variables**

Certain parameters must be provided to integrate a Node.js application with Keycloak. Below is a breakdown of each required variable, its purpose, and where to find it. Here’s what each variable represents:

<table border="1" id="bkmrk-variable-description" style="border-collapse: collapse; border-color: rgb(0, 0, 0); width: 100%;"><thead><tr><th style="border-color: rgb(0, 0, 0); width: 15.8492%;">**Variable**

</th><th style="border-color: rgb(0, 0, 0); width: 44.4607%;">**Description**

</th><th style="border-color: rgb(0, 0, 0); width: 39.6901%;">**Purpose**

</th></tr></thead><tbody><tr><td style="border-color: rgb(0, 0, 0); width: 15.8492%;">`REALM`

</td><td style="border-color: rgb(0, 0, 0); width: 44.4607%;">The realm name from the Keycloak Admin Console

</td><td style="border-color: rgb(0, 0, 0); width: 39.6901%;">Defines the namespace for authentication and authorization

</td></tr><tr><td style="border-color: rgb(0, 0, 0); width: 15.8492%;">`AUTH_SERVER_URL`

</td><td style="border-color: rgb(0, 0, 0); width: 44.4607%;">The full realm URL from Keycloak (e.g., <span class="s1">https://your-domain/realms/xyz</span>)

</td><td style="border-color: rgb(0, 0, 0); width: 39.6901%;">Used as the OIDC issuer base URL

</td></tr><tr><td style="border-color: rgb(0, 0, 0); width: 15.8492%;">`CLIENT_ID`

</td><td style="border-color: rgb(0, 0, 0); width: 44.4607%;">Client ID from the Keycloak Clients page

</td><td style="border-color: rgb(0, 0, 0); width: 39.6901%;">Identifies the application in Keycloak

</td></tr><tr><td style="border-color: rgb(0, 0, 0); width: 15.8492%;">`CLIENT_SECRET`

</td><td style="border-color: rgb(0, 0, 0); width: 44.4607%;">Secret for the OIDC client, found in the Credentials tab of the client

</td><td style="border-color: rgb(0, 0, 0); width: 39.6901%;">Authenticates the Node.js application to Keycloak

</td></tr><tr><td style="border-color: rgb(0, 0, 0); width: 15.8492%;">`REDIRECT_URI`

</td><td style="border-color: rgb(0, 0, 0); width: 44.4607%;">URI where users are redirected after authentication

</td><td style="border-color: rgb(0, 0, 0); width: 39.6901%;">Ensures Keycloak returns control to your app after login

</td></tr></tbody></table>

These values can usually be found in the Keycloak Admin Console under <span class="s1">**Clients**</span> and <span class="s1">**Realm Settings**</span>. Make sure to copy these details and add them to the code moving ahead.

## **Prerequisites**

#### **Install Node.js and NPM**

Check if Node.js is installed by running:

```
node -v
```

If not installed, download it from [https://nodejs.org](https://nodejs.org) and install.

Verify NPM installation:

```
npm -v
```

#### **Install Required Packages**

The <span class="s2">keycloak-connect</span> package enables Node.js applications to authenticate using Keycloak. Install the required packages using:

```
npm install express express-session keycloak-connect
```

## **Code**

Once all prerequisites are set up, create a new file named <span class="s2">keycloak.js</span> and add the following code:

```javascript
const express = require("express");
const session = require("express-session");
const Keycloak = require("keycloak-connect");

const app = express();
const port = process.env.PORT || 3000;

const memoryStore = new session.MemoryStore();

app.use(
  session({
    secret: "supersecret",
    resave: false,
    saveUninitialized: true,
    store: memoryStore,
  })
);

const keycloakConfig = {
  realm: "REALM",
  authServerUrl: "AUTH_SERVER_URL",
  clientId: "CLIENT_ID",
  credentials: {
    secret: "CLIENT_SECRET",
  },
  sslRequired: "external",
  confidentialPort: 0,
};

const keycloak = new Keycloak({ store: memoryStore }, keycloakConfig);
app.use(keycloak.middleware());

app.get("/", (req, res) => {
  res.send("Welcome to the public route.");
});

app.get("/protected", keycloak.protect(), (req, res) => {
  res.send("You have accessed a protected route.");
});

app.get("/logout", (req, res) => {
  req.logout();
  res.redirect("/");
});

app.listen(port, () => {
  console.log(`Server running at http://localhost:${port}`);
});
```

Replace the placeholder values (<span class="s1">REALM</span>, <span class="s1">AUTH\_SERVER\_URL</span>, <span class="s1">CLIENT\_ID</span>, and <span class="s1">CLIENT\_SECRET</span>) with actual values from your Keycloak server.

## **Execution**

Open the terminal or command prompt and navigate to the directory where <span class="s1">keycloak.js</span> is saved. Once in the correct directory, run the script with the command:

```
node keycloak.js
```

If the connection is successful:

1. Visit <span class="s1">http://localhost:3000</span> in your browser to access the public route.
2. Visit <span class="s1">http://localhost:3000/protected</span> to trigger Keycloak authentication.
3. Upon successful login, you’ll be redirected back and see protected content.
4. Visit <span class="s1">http://localhost:3000/logout</span> to log out and end the session.

# Connecting with Python

This guide explains how to establish a connection between a Python Flask application and a Keycloak identity provider using <span class="s2">Flask-OIDC</span>. It walks through the necessary setup, configuration, and usage of a protected route that requires authentication.

## **Variables**

Certain parameters must be provided to integrate a Python Flask application with Keycloak. Below is a breakdown of each required variable, its purpose, and where to find it. Here’s what each variable represents:

<table border="1" id="bkmrk-variable-description" style="width: 100%; border-collapse: collapse; border-color: rgb(0, 0, 0);"><thead><tr><th style="width: 18.1145%; border-color: rgb(0, 0, 0);">**Variable**

</th><th style="width: 43.0297%; border-color: rgb(0, 0, 0);">**Description**

</th><th style="width: 38.8558%; border-color: rgb(0, 0, 0);">**Purpose**

</th></tr></thead><tbody><tr><td style="width: 18.1145%; border-color: rgb(0, 0, 0);">`CLIENT_ID`

</td><td style="width: 43.0297%; border-color: rgb(0, 0, 0);">Client ID from the Keycloak Clients page

</td><td style="width: 38.8558%; border-color: rgb(0, 0, 0);">Identifies the Flask app in the Keycloak realm

</td></tr><tr><td style="width: 18.1145%; border-color: rgb(0, 0, 0);">`CLIENT_SECRET`

</td><td style="width: 43.0297%; border-color: rgb(0, 0, 0);">Secret from the Credentials tab of the client

</td><td style="width: 38.8558%; border-color: rgb(0, 0, 0);">Authenticates the Flask app with Keycloak

</td></tr><tr><td style="width: 18.1145%; border-color: rgb(0, 0, 0);">`ISSUER`

</td><td style="width: 43.0297%; border-color: rgb(0, 0, 0);"><span class="s1">Full Keycloak realm URL (e.g. </span>https://your-domain/realms/your-realm<span class="s1">)</span>

</td><td style="width: 38.8558%; border-color: rgb(0, 0, 0);">Defines the OpenID Connect issuer

</td></tr><tr><td style="width: 18.1145%; border-color: rgb(0, 0, 0);">`REDIRECT_URI`

</td><td style="width: 43.0297%; border-color: rgb(0, 0, 0);">The callback URL Keycloak will redirect to after login

</td><td style="width: 38.8558%; border-color: rgb(0, 0, 0);">Used by Flask-OIDC to complete login flow

</td></tr><tr><td style="width: 18.1145%; border-color: rgb(0, 0, 0);">`TOKEN_ENDPOINT`

</td><td style="width: 43.0297%; border-color: rgb(0, 0, 0);">Token URL from Keycloak

</td><td style="width: 38.8558%; border-color: rgb(0, 0, 0);">Used for exchanging authorization codes for access tokens

</td></tr><tr><td style="width: 18.1145%; border-color: rgb(0, 0, 0);">`USERINFO_ENDPOINT`

</td><td style="width: 43.0297%; border-color: rgb(0, 0, 0);">User info endpoint from Keycloak

</td><td style="width: 38.8558%; border-color: rgb(0, 0, 0);">Used to fetch user profile after login

</td></tr></tbody></table>

These values can be found in the <span class="s1">**Keycloak Admin Console**</span> under <span class="s1">**Clients → \[Your Client\] → Settings / Credentials / Endpoints**</span>. Make sure to copy and add them to the code as shown.

## **Prerequisites**

#### **Install Python and pip**

Check if Python is installed by running:

```
python3 --version
```

If not installed, download it from [https://python.org](https://python.org) and install.

Verify <span class="s1">pip</span> installation:

```
pip3 --version
```

#### **Install Required Packages**

Install the required Python packages using:

```
pip3 install flask flask-oidc
```

## **Code**

Once all prerequisites are set up, create a new file named <span class="s2">app.py</span> and add the following code:

```python
from flask import Flask, redirect, url_for, jsonify
from flask_oidc import OpenIDConnect

app = Flask(__name__)

# Keycloak OIDC configuration (no JSON file required)
app.config.update({
    'SECRET_KEY': 'your-random-secret',
    'OIDC_CLIENT_SECRETS': {
        "web": {
            "client_id": "CLIENT_ID",
            "client_secret": "CLIENT_SECRET",
            "auth_uri": "https://your-keycloak-domain/realms/your-realm/protocol/openid-connect/auth",
            "token_uri": "https://your-keycloak-domain/realms/your-realm/protocol/openid-connect/token",
            "userinfo_uri": "https://your-keycloak-domain/realms/your-realm/protocol/openid-connect/userinfo",
            "redirect_uris": ["http://localhost:5000/oidc/callback"]
        }
    },
    'OIDC_SCOPES': ['openid', 'email', 'profile'],
    'OIDC_CALLBACK_ROUTE': '/oidc/callback',
    'OIDC_COOKIE_SECURE': False
})

oidc = OpenIDConnect(app)

@app.route('/')
def index():
    return 'Welcome to the public route.'

@app.route('/protected')
@oidc.require_login
def protected():
    user_info = oidc.user_getinfo(['email', 'sub', 'name'])
    return jsonify({
        "message": "You are authenticated",
        "user": user_info
    })

@app.route('/logout')
def logout():
    oidc.logout()
    return redirect(url_for('index'))

if __name__ == '__main__':
    app.run(debug=True)
```

Replace the placeholders in the <span class="s1">client\_id</span>, <span class="s1">client\_secret</span>, and URL fields with actual values from your Keycloak instance.

## **Execution**

Open the terminal and navigate to the directory where <span class="s1">app.py</span> is saved. Once in the correct directory, run the script with the command:

```
python3 app.py
```

If the connection is successful:

1. Open <span class="s1">http://localhost:5000</span> in your browser — Public route.
2. Open <span class="s1">http://localhost:5000/protected</span> — Redirects to Keycloak login.
3. After logging in, you’ll see user info returned from the protected route.
4. Visit <span class="s1">http://localhost:5000/logout</span> to end the session and return to the public page.

# Connecting with PHP

This guide explains how to establish a connection between a PHP application and a Keycloak identity provider using the <span class="s2">jumbojett/openid-connect-php</span> library. It walks through the necessary setup, configuration, and execution of a protected login route using OpenID Connect (OIDC).

## **Variables**

Certain parameters must be provided to integrate a PHP application with Keycloak. Below is a breakdown of each required variable, its purpose, and where to find it. Here’s what each variable represents:

<table border="1" id="bkmrk-variable-description" style="border-collapse: collapse; border-color: rgb(0, 0, 0); width: 100%; height: 275.766px;"><thead><tr style="height: 29.7969px;"><th style="border-color: rgb(0, 0, 0); width: 16.209%; height: 29.7969px;">**Variable**

</th><th style="border-color: rgb(0, 0, 0); width: 45.2995%; height: 29.7969px;">**Description**

</th><th style="border-color: rgb(0, 0, 0); width: 38.3724%; height: 29.7969px;">**Purpose**

</th></tr></thead><tbody><tr style="height: 29.7969px;"><td style="border-color: rgb(0, 0, 0); width: 16.209%; height: 29.7969px;">`CLIENT_ID`

</td><td style="border-color: rgb(0, 0, 0); width: 45.2995%; height: 29.7969px;">Client ID from the Keycloak Admin Console

</td><td style="border-color: rgb(0, 0, 0); width: 38.3724%; height: 29.7969px;">Identifies the PHP app in the Keycloak realm

</td></tr><tr style="height: 29.7969px;"><td style="border-color: rgb(0, 0, 0); width: 16.209%; height: 29.7969px;">`CLIENT_SECRET`

</td><td style="border-color: rgb(0, 0, 0); width: 45.2995%; height: 29.7969px;">Secret from the Client &gt; Credentials tab

</td><td style="border-color: rgb(0, 0, 0); width: 38.3724%; height: 29.7969px;">Authenticates the PHP app with Keycloak

</td></tr><tr style="height: 46.5938px;"><td style="border-color: rgb(0, 0, 0); width: 16.209%; height: 46.5938px;">`ISSUER`

</td><td style="border-color: rgb(0, 0, 0); width: 45.2995%; height: 46.5938px;"><span class="s1">The Keycloak realm URL (e.g., </span>https://your-domain/realms/your-realm<span class="s1">)</span>

</td><td style="border-color: rgb(0, 0, 0); width: 38.3724%; height: 46.5938px;">Acts as the OIDC issuer and discovery endpoint

</td></tr><tr style="height: 46.5938px;"><td style="border-color: rgb(0, 0, 0); width: 16.209%; height: 46.5938px;">`REDIRECT_URI`

</td><td style="border-color: rgb(0, 0, 0); width: 45.2995%; height: 46.5938px;">The URI that Keycloak will redirect to after login

</td><td style="border-color: rgb(0, 0, 0); width: 38.3724%; height: 46.5938px;">Where the user will be sent after successful authentication

</td></tr><tr style="height: 46.5938px;"><td style="border-color: rgb(0, 0, 0); width: 16.209%; height: 46.5938px;">`TOKEN_ENDPOINT`

</td><td style="border-color: rgb(0, 0, 0); width: 45.2995%; height: 46.5938px;">Token URL under the selected realm

</td><td style="border-color: rgb(0, 0, 0); width: 38.3724%; height: 46.5938px;">Used to retrieve access/ID tokens

</td></tr><tr style="height: 46.5938px;"><td style="border-color: rgb(0, 0, 0); width: 16.209%; height: 46.5938px;">`USERINFO_ENDPOINT`

</td><td style="border-color: rgb(0, 0, 0); width: 45.2995%; height: 46.5938px;">URL to fetch user profile information

</td><td style="border-color: rgb(0, 0, 0); width: 38.3724%; height: 46.5938px;">Used to retrieve authenticated user details

</td></tr></tbody></table>

These values can be copied from the Keycloak Admin Console under <span class="s1">**Clients &gt; \[Your Client\] &gt; Endpoints**</span>.

## **Prerequisites**

#### **Install PHP and Composer**

Ensure PHP is installed:

```
php -v
```

Install Composer (PHP dependency manager) if not already installed:

```
composer --version
```

If not installed, visit [https://getcomposer.org](https://getcomposer.org) and follow the install instructions

#### **Install Required Package**

Install the <span class="s2">jumbojett/openid-connect-php</span> package using Composer:

```
composer require jumbojett/openid-connect-php
```

## **Code**

Once all prerequisites are set up, create a file named <span class="s2">keycloak.php</span> and add the following code:

```php
<?php
require_once __DIR__ . '/vendor/autoload.php';

use Jumbojett\OpenIDConnectClient;

$oidc = new OpenIDConnectClient(
    'https://your-keycloak-domain/realms/your-realm',
    'CLIENT_ID',
    'CLIENT_SECRET'
);

// Optional config
$oidc->setRedirectURL('http://localhost:8000/keycloak.php');
$oidc->setProviderConfigParams([
    'token_endpoint' => 'https://your-keycloak-domain/realms/your-realm/protocol/openid-connect/token',
    'userinfo_endpoint' => 'https://your-keycloak-domain/realms/your-realm/protocol/openid-connect/userinfo'
]);

// Start login flow
$oidc->authenticate();

// Show user info
$userInfo = $oidc->requestUserInfo();

echo "<h1>Welcome, " . htmlspecialchars($userInfo->preferred_username) . "</h1>";
echo "";
print_r($userInfo);
echo "";
?>
```

Replace:

- https://your-keycloak-domain/realms/your-realm<span class="s1"> with your actual realm URL</span>
- <span class="s1">CLIENT\_ID</span> and <span class="s1">CLIENT\_SECRET</span> with credentials from the Keycloak client settings
- <span class="s1">http://localhost:8000/keycloak.php</span> with your desired callback/redirect URI

Ensure the <span class="s2">**Valid Redirect URIs**</span> field in Keycloak matches the above redirect URI.

## **Execution**

Start a PHP development server in the directory containing <span class="s3">keycloak.php</span>:

```
php -S localhost:8000
```

Open your browser and navigate to:

```
http://localhost:8000/keycloak.php
```

If the connection is successful:

1. You’ll be redirected to the Keycloak login page.
2. After authentication, you’ll be redirected back to the PHP script.
3. The user profile will be displayed using data returned from Keycloak.

# Connecting with Go

This guide explains how to establish a connection between a Go application and a Keycloak identity provider using the OIDC (OpenID Connect) protocol. It walks through the necessary setup, configuration, and execution of a basic login flow to authenticate users through Keycloak.

## **Variables**

Certain parameters must be provided to integrate a Go application with Keycloak. Below is a breakdown of each required variable, its purpose, and where to find it. Here’s what each variable represents:

<table border="1" id="bkmrk-variable-description" style="border-collapse: collapse; border-color: rgb(0, 0, 0);"><thead><tr><th style="border-color: rgb(0, 0, 0);">**Variable**

</th><th style="border-color: rgb(0, 0, 0);">**Description**

</th><th style="border-color: rgb(0, 0, 0);">**Purpose**

</th></tr></thead><tbody><tr><td style="border-color: rgb(0, 0, 0);">`CLIENT_ID`

</td><td style="border-color: rgb(0, 0, 0);">Client ID from the Keycloak Admin Console

</td><td style="border-color: rgb(0, 0, 0);">Identifies the Go app in the Keycloak realm

</td></tr><tr><td style="border-color: rgb(0, 0, 0);">`CLIENT_SECRET`

</td><td style="border-color: rgb(0, 0, 0);">Secret from the Credentials tab of the client

</td><td style="border-color: rgb(0, 0, 0);">Authenticates the Go app with Keycloak

</td></tr><tr><td style="border-color: rgb(0, 0, 0);">`ISSUER_URL`

</td><td style="border-color: rgb(0, 0, 0);"><span class="s1">Realm URL (e.g., </span>https://your-domain/realms/your-realm<span class="s1">)</span>

</td><td style="border-color: rgb(0, 0, 0);">Base URL for OIDC discovery and validation

</td></tr><tr><td style="border-color: rgb(0, 0, 0);">`REDIRECT_URL`

</td><td style="border-color: rgb(0, 0, 0);">The callback URL Keycloak redirects to after successful login

</td><td style="border-color: rgb(0, 0, 0);">Required to complete the OIDC flow

</td></tr></tbody></table>

These values are found under <span class="s1">**Clients &gt; \[Your Client\] &gt; Settings / Endpoints**</span> in the Keycloak Admin Console.

## **Prerequisites**

##### **Install Go**

Check if Go is installed:

```
go version
```

If not installed, download it from [https://golang.org/dl](https://golang.org/dl) and install.

##### **Install Required Packages**

Install the required Go packages:

```
go get github.com/coreos/go-oidc/v3
go get golang.org/x/oauth2
```

## **Code**

Once all prerequisites are set up, create a new file named <span class="s2">main.go</span> and add the following code:

```go
package main

import (
	"context"
	"fmt"
	"log"
	"net/http"

	"golang.org/x/oauth2"
	"golang.org/x/oauth2/clientcredentials"
	"golang.org/x/oauth2/endpoints"
	"github.com/coreos/go-oidc/v3/oidc"
)

var (
	clientID     = "CLIENT_ID"
	clientSecret = "CLIENT_SECRET"
	redirectURL  = "http://localhost:8080/callback"
	issuerURL    = "https://your-keycloak-domain/realms/your-realm"
)

func main() {
	ctx := context.Background()

	provider, err := oidc.NewProvider(ctx, issuerURL)
	if err != nil {
		log.Fatalf("Failed to get provider: %v", err)
	}

	verifier := provider.Verifier(&oidc.Config{ClientID: clientID})

	config := oauth2.Config{
		ClientID:     clientID,
		ClientSecret: clientSecret,
		Endpoint:     provider.Endpoint(),
		Scopes:       []string{oidc.ScopeOpenID, "profile", "email"},
		RedirectURL:  redirectURL,
	}

	http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
		url := config.AuthCodeURL("state", oauth2.AccessTypeOffline)
		http.Redirect(w, r, url, http.StatusFound)
	})

	http.HandleFunc("/callback", func(w http.ResponseWriter, r *http.Request) {
		ctx := r.Context()
		if r.URL.Query().Get("state") != "state" {
			http.Error(w, "state mismatch", http.StatusBadRequest)
			return
		}

		oauth2Token, err := config.Exchange(ctx, r.URL.Query().Get("code"))
		if err != nil {
			http.Error(w, "failed to exchange token: "+err.Error(), http.StatusInternalServerError)
			return
		}

		rawIDToken, ok := oauth2Token.Extra("id_token").(string)
		if !ok {
			http.Error(w, "no id_token field in oauth2 token", http.StatusInternalServerError)
			return
		}

		idToken, err := verifier.Verify(ctx, rawIDToken)
		if err != nil {
			http.Error(w, "failed to verify ID Token: "+err.Error(), http.StatusInternalServerError)
			return
		}

		var claims map[string]interface{}
		if err := idToken.Claims(&claims); err != nil {
			http.Error(w, "failed to parse claims: "+err.Error(), http.StatusInternalServerError)
			return
		}

		fmt.Fprintf(w, "Login successful! User info:\n\n%v", claims)
	})

	log.Println("Server started at http://localhost:8080")
	log.Fatal(http.ListenAndServe(":8080", nil))
}
```

Replace:

- <span class="s1">CLIENT\_ID</span> and <span class="s1">CLIENT\_SECRET</span> with your Keycloak client credentials
- https://your-keycloak-domain/realms/your-realm<span class="s1"> with your realm’s base URL</span>
- <span class="s1">http://localhost:8080/callback</span> should be registered in Keycloak’s <span class="s2">**Valid Redirect URIs**</span>

## **Execute**

1. Run the application with:

```
go run main.go
```

2. In your browser, navigate to:

```
http://localhost:8080
```

3. You will be redirected to the Keycloak login screen. After logging in:

- The app will redirect to <span class="s1">/callback</span>
- If successful, you’ll see your decoded user info printed on the screen

# Connecting with Java

This guide explains how to establish a connection between a Java Spring Boot application and a Keycloak identity provider using the OAuth2 resource server configuration. It walks through the necessary setup, configuration, and creation of a protected endpoint that verifies Keycloak-issued access tokens.

## **Variables**

Certain parameters must be provided to integrate a Spring Boot application with Keycloak. Below is a breakdown of each required variable, its purpose, and where to find it. Here’s what each variable represents:

<table border="1" id="bkmrk-variable-description" style="width: 100%; border-collapse: collapse; border-color: rgb(0, 0, 0);"><thead><tr><th style="width: 12.5123%; border-color: rgb(0, 0, 0);">**Variable**

</th><th style="width: 47.5592%; border-color: rgb(0, 0, 0);">**Description**

</th><th style="width: 39.9285%; border-color: rgb(0, 0, 0);">**Purpose**

</th></tr></thead><tbody><tr><td style="width: 12.5123%; border-color: rgb(0, 0, 0);">`REALM`

</td><td style="width: 47.5592%; border-color: rgb(0, 0, 0);">The name of the Keycloak realm

</td><td style="width: 39.9285%; border-color: rgb(0, 0, 0);">Defines the authentication namespace

</td></tr><tr><td style="width: 12.5123%; border-color: rgb(0, 0, 0);">`CLIENT_ID`

</td><td style="width: 47.5592%; border-color: rgb(0, 0, 0);">Client ID from the Keycloak Admin Console

</td><td style="width: 39.9285%; border-color: rgb(0, 0, 0);">Identifies the Spring Boot app in Keycloak

</td></tr><tr><td style="width: 12.5123%; border-color: rgb(0, 0, 0);">`ISSUER_URI`

</td><td style="width: 47.5592%; border-color: rgb(0, 0, 0);"><span class="s1">Realm URL (e.g. </span>https://your-domain/realms/your-realm<span class="s1">)</span>

</td><td style="width: 39.9285%; border-color: rgb(0, 0, 0);">Used by Spring Security for token validation

</td></tr><tr><td style="width: 12.5123%; border-color: rgb(0, 0, 0);">`JWKS_URI`

</td><td style="width: 47.5592%; border-color: rgb(0, 0, 0);">URL to the JWKS endpoint (auto-resolved by Spring from ISSUER\_URI)

</td><td style="width: 39.9285%; border-color: rgb(0, 0, 0);">Used to fetch public keys for token signature verification

</td></tr></tbody></table>

These values can be found in the <span class="s1">**Keycloak Admin Console → Clients**</span> and under the <span class="s1">**OpenID Connect Endpoints**</span> section for your realm.

## **Prerequisites**

#### **Install Java and Maven**

Ensure Java is installed:

```
java -version
```

Ensure Maven is installed:

```
mvn -version
```

If not, download and install from [https://adoptium.net](https://adoptium.net) or [https://maven.apache.org](https://maven.apache.org).

## **Code**

Once all prerequisites are set up, create a new Spring Boot project with the following structure:

```
spring-keycloak-demo/
├── src/
│   └── main/
│       ├── java/com/example/demo/
│       │   ├── DemoApplication.java
│       │   └── HelloController.java
│       └── resources/
│           └── application.yml
├── pom.xml
```

**pom.xml**

```xml
<project xmlns="http://maven.apache.org/POM/4.0.0" ...>
  <modelVersion>4.0.0</modelVersion>
  <groupId>com.example</groupId>
  <artifactId>spring-keycloak-demo</artifactId>
  <version>0.0.1-SNAPSHOT</version>
  <properties>
    <java.version>17</java.version>
    <spring.boot.version>3.1.5</spring.boot.version>
  </properties>

  <dependencies>
    <dependency>
      <groupId>org.springframework.boot</groupId>
      <artifactId>spring-boot-starter-web</artifactId>
    </dependency>
    <dependency>
      <groupId>org.springframework.boot</groupId>
      <artifactId>spring-boot-starter-oauth2-resource-server</artifactId>
    </dependency>
  </dependencies>

  <build>
    <plugins>
      <plugin>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-maven-plugin</artifactId>
      </plugin>
    </plugins>
  </build>
</project>
```

**application.yml**

```yaml
server:
  port: 8080

spring:
  security:
    oauth2:
      resourceserver:
        jwt:
          issuer-uri: https://your-keycloak-domain/realms/your-realm
```

Replace <span class="s1">https://your-keycloak-domain/realms/your-realm</span> with the full issuer URI from your Keycloak realm.

**DemoApplication.java**

```java
package com.example.demo;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class DemoApplication {
  public static void main(String[] args) {
    SpringApplication.run(DemoApplication.class, args);
  }
}
```

**HelloController.java**

```java
package com.example.demo;

import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.security.core.annotation.AuthenticationPrincipal;
import org.springframework.security.oauth2.jwt.Jwt;

@RestController
public class HelloController {

  @GetMapping("/")
  public String publicEndpoint() {
    return "Welcome to the public endpoint.";
  }

  @GetMapping("/protected")
  public String protectedEndpoint(@AuthenticationPrincipal Jwt jwt) {
    return "Hello " + jwt.getClaimAsString("preferred_username") + ", you have accessed a protected route.";
  }
}
```

## **Execution**

1. Start the Spring Boot app with:

```
mvn spring-boot:run
```

2. Generate a JWT access token by logging in through your frontend or REST client (e.g., using Postman with client credentials).
3. Make a request to:

```
GET http://localhost:8080/protected
Authorization: Bearer <access_token>
```

If the token is valid:

- You will receive a welcome message with the Keycloak username
- If no token is provided or it’s invalid, you’ll get a <span class="s1">401 Unauthorized</span> error

# Connecting with Frontend Applications

This guide explains how to establish a connection between a frontend single-page application (SPA) — such as those built with React, Vue, or Angular and a Keycloak identity provider using the official Keycloak JavaScript adapter. It walks through the necessary setup, configuration, and execution of a protected login flow.

## **Variables**

Certain parameters must be provided to integrate a frontend application with Keycloak. Below is a breakdown of each required variable, its purpose, and where to find it. Here’s what each variable represents:

<table border="1" id="bkmrk-variable-description" style="border-collapse: collapse; border-color: rgb(0, 0, 0); width: 100%;"><thead><tr><th style="border-color: rgb(0, 0, 0); width: 14.6561%;">**Variable**

</th><th style="border-color: rgb(0, 0, 0); width: 41.6014%;">**Description**

</th><th style="border-color: rgb(0, 0, 0); width: 43.7426%;">**Purpose**

</th></tr></thead><tbody><tr><td style="border-color: rgb(0, 0, 0); width: 14.6561%;">`URL`

</td><td style="border-color: rgb(0, 0, 0); width: 41.6014%;"><span class="s1">Full Keycloak realm URL (e.g., </span>https://your-domain/realms/your-realm<span class="s1">)</span>

</td><td style="border-color: rgb(0, 0, 0); width: 43.7426%;">The base endpoint for authentication, token requests, and user info

</td></tr><tr><td style="border-color: rgb(0, 0, 0); width: 14.6561%;">`CLIENT_ID`

</td><td style="border-color: rgb(0, 0, 0); width: 41.6014%;">Client ID from the Keycloak Admin Console

</td><td style="border-color: rgb(0, 0, 0); width: 43.7426%;">Identifies the SPA in Keycloak

</td></tr><tr><td style="border-color: rgb(0, 0, 0); width: 14.6561%;">`REALM`

</td><td style="border-color: rgb(0, 0, 0); width: 41.6014%;">The realm name where the client is defined

</td><td style="border-color: rgb(0, 0, 0); width: 43.7426%;">Defines the identity space

</td></tr><tr><td style="border-color: rgb(0, 0, 0); width: 14.6561%;">`REDIRECT_URI`

</td><td style="border-color: rgb(0, 0, 0); width: 41.6014%;">The URL where the frontend app should return after login

</td><td style="border-color: rgb(0, 0, 0); width: 43.7426%;">Must be registered in Keycloak as a Valid Redirect URI

</td></tr></tbody></table>

These values can be found under <span class="s1">**Clients &gt; \[Your Client\] &gt; Settings**</span> in the Keycloak Admin Console.

## **Prerequisites**

#### **Install Node.js and NPM**

Check if Node.js is installed:

```
node -v
```

If not, download and install from [https://nodejs.org](https://nodejs.org).

#### **Set Up Frontend Project**

Create a frontend project using your framework of choice. For example:

- **React:**

```
npx create-react-app keycloak-app
cd keycloak-app
```

- **Vue:**

```
npm init vue@latest
cd keycloak-app
```

- **Angular:**

```
ng new keycloak-app
cd keycloak-app
```

Then install the Keycloak JS adapter:

```
npm install keycloak-js
```

## **Code**

Create a file named <span class="s2">keycloak.js</span> inside your <span class="s2">src/</span> directory with the following content:

```javascript
import Keycloak from "keycloak-js";

const keycloak = new Keycloak({
  url: "https://your-keycloak-domain",
  realm: "your-realm",
  clientId: "your-client-id",
});

export default keycloak;
```

Then update your app’s entry point (<span class="s1">App.js</span>, <span class="s1">main.js</span>, or <span class="s1">main.ts</span>) to initialize Keycloak:

### **Example (React - App.js):**

```javascript
import React, { useEffect, useState } from "react";
import keycloak from "./keycloak";

function App() {
  const [authenticated, setAuthenticated] = useState(false);

  useEffect(() => {
    keycloak.init({ onLoad: "login-required" }).then((auth) => {
      setAuthenticated(auth);
    });
  }, []);

  if (!authenticated) return <div>Loading...</div>;

  return (
    <div>
      <h1>Welcome, {keycloak.tokenParsed?.preferred_username}</h1>
      <p>You have accessed a protected frontend app using Keycloak.</p>
    </div>
  );
}

export default App;
```

##### **Notes for Vue and Angular**

- In Vue, you can wrap <span class="s1">keycloak.init()</span> inside a plugin and gate your app rendering using the <span class="s1">onReady()</span> hook.
- In Angular, use route guards (<span class="s1">CanActivate</span>) to protect routes based on Keycloak session state.

## **Execution**

1. Replace all placeholders in the config with actual values from your Keycloak setup.
2. Start your frontend application:

```
npm start
```

3. Open your browser and navigate to:

```
http://localhost:3000
```

4. The Keycloak login page will appear. After authentication:
    
    
    - You’ll be redirected back to your SPA
    - The user info will be displayed, indicating successful integration

# Connecting with Keycloak Admin Rest API

This guide explains how to authenticate with and use the Keycloak Admin REST API from a backend application. It walks through the necessary setup, authentication flow, and execution of a sample API request to list users in a realm.

## **Variables**

Certain parameters must be provided to access the Keycloak Admin REST API successfully. Below is a breakdown of each required variable, its purpose, and where to find it. Here’s what each variable represents:

<table border="1" id="bkmrk-variable-description" style="border-collapse: collapse; border-color: rgb(0, 0, 0); width: 100%;"><thead><tr><th style="border-color: rgb(0, 0, 0); width: 16.5648%;">**Variable**

</th><th style="border-color: rgb(0, 0, 0); width: 44.3411%;">**Description**

</th><th style="border-color: rgb(0, 0, 0); width: 39.0942%;">**Purpose**

</th></tr></thead><tbody><tr><td style="border-color: rgb(0, 0, 0); width: 16.5648%;">`BASE_URL`

</td><td style="border-color: rgb(0, 0, 0); width: 44.3411%;">The base URL of the Keycloak server (e.g., <span class="s1">https://your-domain</span>)

</td><td style="border-color: rgb(0, 0, 0); width: 39.0942%;">All admin API requests are made under this URL

</td></tr><tr><td style="border-color: rgb(0, 0, 0); width: 16.5648%;">`REALM`

</td><td style="border-color: rgb(0, 0, 0); width: 44.3411%;">The realm name used to obtain an admin access token

</td><td style="border-color: rgb(0, 0, 0); width: 39.0942%;">Typically <span class="s1">"master"</span> if accessing all realms, or your target realm

</td></tr><tr><td style="border-color: rgb(0, 0, 0); width: 16.5648%;">`CLIENT_ID`

</td><td style="border-color: rgb(0, 0, 0); width: 44.3411%;">The client ID configured for admin access (must have sufficient privileges)

</td><td style="border-color: rgb(0, 0, 0); width: 39.0942%;">Authenticates the backend to obtain an access token

</td></tr><tr><td style="border-color: rgb(0, 0, 0); width: 16.5648%;">`CLIENT_SECRET`

</td><td style="border-color: rgb(0, 0, 0); width: 44.3411%;">The client secret associated with the client

</td><td style="border-color: rgb(0, 0, 0); width: 39.0942%;">Required to authenticate confidential clients

</td></tr><tr><td style="border-color: rgb(0, 0, 0); width: 16.5648%;">`ADMIN_USERNAME`

</td><td style="border-color: rgb(0, 0, 0); width: 44.3411%;">A Keycloak admin user with the <span class="s1">manage-users</span> or <span class="s1">admin</span> role

</td><td style="border-color: rgb(0, 0, 0); width: 39.0942%;">Used in password grant to fetch an access token

</td></tr><tr><td style="border-color: rgb(0, 0, 0); width: 16.5648%;">`ADMIN_PASSWORD`

</td><td style="border-color: rgb(0, 0, 0); width: 44.3411%;">The password for the above admin user

</td><td style="border-color: rgb(0, 0, 0); width: 39.0942%;">Used with the username to authenticate

</td></tr></tbody></table>

<span class="s1">These values can be found in the </span>**Keycloak Admin Console**<span class="s1"> under </span>**Clients &gt; \[Your Admin Client\]**<span class="s1"> and </span>**Users &gt; \[Admin User\]**<span class="s1">.</span>

## **Prerequisites**

#### **Install Node.js and NPM**

Check if Node.js is installed:

```
node -v
```

Verify npm installation:

```
npm -v
```

#### **Install Required Package**

We’ll use Axios to make HTTP requests. Install it with:

```
npm install axios
```

## **Code**

Once all prerequisites are set up, create a new file named <span class="s2">admin-api.js</span> and add the following code:

```javascript
const axios = require("axios");

const BASE_URL = "https://your-keycloak-domain";
const REALM = "master";
const CLIENT_ID = "admin-cli";
const ADMIN_USERNAME = "your-admin-username";
const ADMIN_PASSWORD = "your-admin-password";

async function getAccessToken() {
  const response = await axios.post(
    `${BASE_URL}/realms/${REALM}/protocol/openid-connect/token`,
    new URLSearchParams({
      client_id: CLIENT_ID,
      grant_type: "password",
      username: ADMIN_USERNAME,
      password: ADMIN_PASSWORD,
    }),
    {
      headers: {
        "Content-Type": "application/x-www-form-urlencoded",
      },
    }
  );
  return response.data.access_token;
}

async function listUsers() {
  try {
    const token = await getAccessToken();
    const response = await axios.get(
      `${BASE_URL}/admin/realms/${REALM}/users`,
      {
        headers: {
          Authorization: `Bearer ${token}`,
        },
      }
    );

    console.log("Users in realm:", response.data);
  } catch (err) {
    console.error("Failed to list users:", err.response?.data || err.message);
  }
}

listUsers();
```

Replace:

- <span class="s1">BASE\_URL</span> with your Keycloak server base URL
- <span class="s1">ADMIN\_USERNAME</span> and <span class="s1">ADMIN\_PASSWORD</span> with your actual admin user credentials
- <span class="s1">REALM</span> with <span class="s1">master</span> (or a custom realm if you configured admin access)

## **Execution**

Open the terminal and navigate to the directory where <span class="s2">admin-api.js</span> is saved. Once in the correct directory, run the script with the command:

```
node admin-api.js
```

If the connection is successful:

1. The script will authenticate using the <span class="s1">password</span> grant type
2. It will retrieve a valid admin access token
3. It will fetch and display the list of users in the specified realm

If an error occurs (such as a 401 unauthorized), double-check your admin credentials and client permissions.

# Connecting External Identity Providers

This guide explains how to integrate external identity providers (IdPs) like <span class="s3">**Google, GitHub, Facebook**</span>, or <span class="s3">**LDAP/Active Directory**</span> into a Keycloak realm. It walks through the necessary setup, configuration, and execution of a login flow that delegates authentication to the external provider.

## **Variables**

Certain parameters must be provided to integrate an external identity provider into Keycloak. Below is a breakdown of each required variable, its purpose, and where to find it. Here’s what each variable represents:

<table border="1" id="bkmrk-variable-description" style="width: 100%; border-collapse: collapse; border-color: rgb(0, 0, 0);"><thead><tr><th style="width: 15.4922%; border-color: rgb(0, 0, 0);">**Variable**

</th><th style="width: 42.3147%; border-color: rgb(0, 0, 0);">**Description**

</th><th style="width: 42.1931%; border-color: rgb(0, 0, 0);">**Purpose**

</th></tr></thead><tbody><tr><td style="width: 15.4922%; border-color: rgb(0, 0, 0);">`IDP_ALIAS`

</td><td style="width: 42.3147%; border-color: rgb(0, 0, 0);">Unique alias name for the identity provider in Keycloak

</td><td style="width: 42.1931%; border-color: rgb(0, 0, 0);">Used to identify and manage the identity provider internally

</td></tr><tr><td style="width: 15.4922%; border-color: rgb(0, 0, 0);">`CLIENT_ID`

</td><td style="width: 42.3147%; border-color: rgb(0, 0, 0);">OAuth2/OpenID Connect Client ID provided by the external IdP

</td><td style="width: 42.1931%; border-color: rgb(0, 0, 0);">Authenticates Keycloak with the external provider

</td></tr><tr><td style="width: 15.4922%; border-color: rgb(0, 0, 0);">`CLIENT_SECRET`

</td><td style="width: 42.3147%; border-color: rgb(0, 0, 0);">Client secret provided by the external IdP

</td><td style="width: 42.1931%; border-color: rgb(0, 0, 0);">Used for secure communication with the IdP

</td></tr><tr><td style="width: 15.4922%; border-color: rgb(0, 0, 0);">`AUTH_URL`

</td><td style="width: 42.3147%; border-color: rgb(0, 0, 0);">Authorization endpoint of the external provider

</td><td style="width: 42.1931%; border-color: rgb(0, 0, 0);">Used to start the OAuth2 login flow

</td></tr><tr><td style="width: 15.4922%; border-color: rgb(0, 0, 0);">`TOKEN_URL`

</td><td style="width: 42.3147%; border-color: rgb(0, 0, 0);">Token endpoint of the external provider

</td><td style="width: 42.1931%; border-color: rgb(0, 0, 0);">Used to exchange authorization code for access token

</td></tr><tr><td style="width: 15.4922%; border-color: rgb(0, 0, 0);">`USERINFO_URL`

</td><td style="width: 42.3147%; border-color: rgb(0, 0, 0);">User info endpoint of the external provider (for OIDC)

</td><td style="width: 42.1931%; border-color: rgb(0, 0, 0);">Fetches profile info for the logged-in user

</td></tr></tbody></table>

These values are available from the external identity provider’s developer console (e.g., Google Cloud Console, GitHub Developer Settings, Facebook for Developers, or LDAP configuration).

## **Prerequisites**

#### **Keycloak Admin Access**

Make sure you are logged into the Keycloak Admin Console with sufficient permissions to:

- Modify identity providers
- Configure clients and mappers
- Assign default roles or groups (optional)

#### **External Provider Setup**

You must first register your Keycloak app with the external identity provider (e.g., Google, GitHub, etc.) and obtain the <span class="s2">**client ID**</span> and <span class="s2">**client secret**</span>, along with <span class="s2">**redirect URI**</span>.

Example (Google):

- Go to [https://console.cloud.google.com](https://console.cloud.google.com)
- Register a new OAuth2 Client under <span class="s1">**APIs &amp; Services &gt; Credentials**</span>
- Set redirect URI to:

```
https://<keycloak-domain>/realms/<your-realm>/broker/google/endpoint
```

## **Code-Free Setup (via Keycloak Admin UI)**

1. **Go to your realm &gt; Identity Providers**
2. **Click “Add provider” → Choose from list (e.g., Google, GitHub, Facebook, etc.)**
    
    [![image.png](https://docs.elest.io/uploads/images/gallery/2025-06/scaled-1680-/72Yimage.png)](https://docs.elest.io/uploads/images/gallery/2025-06/72Yimage.png)
3. Enter the required fields:
    
    
    - <span class="s1">**Alias**</span><span class="s2">: </span>google<span class="s2">, </span>github<span class="s2">, etc.</span>
    - <span class="s1">**Client ID**</span>: From the external IdP
    - <span class="s1">**Client Secret**</span>: From the external IdP
4. Configure <span class="s1">**Default Scopes**</span> and any user attribute mappers (e.g., email, name)
5. Enable the provider by checking <span class="s1">**“Enabled”**</span>
6. Save

You’ll now see the provider appear on your login page as a social button or link.

## **LDAP / Active Directory Integration**

For enterprise identity backends like <span class="s2">**LDAP**</span> or <span class="s2">**Active Directory**</span>, follow these steps:

- <span class="s1">Go to </span>**User Federation &gt; Add Provider → LDAP**
- Fill in the following fields:

<table id="bkmrk-field-example-connec" style="width: 55.7143%;"><thead><tr><th style="width: 26.1242%;">**Field**

</th><th style="width: 73.8758%;">**Example**

</th></tr></thead><tbody><tr><td style="width: 26.1242%;">Connection URL

</td><td style="width: 73.8758%;">ldap://ldap.mycompany.com

</td></tr><tr><td style="width: 26.1242%;">Users DN

</td><td style="width: 73.8758%;">ou=users,dc=mycompany,dc=com

</td></tr><tr><td style="width: 26.1242%;">Bind DN

</td><td style="width: 73.8758%;">cn=admin,dc=mycompany,dc=com

</td></tr><tr><td style="width: 26.1242%;">Bind Credential

</td><td style="width: 73.8758%;">Your LDAP admin password

</td></tr><tr><td style="width: 26.1242%;">Vendor

</td><td style="width: 73.8758%;">Choose from Active Directory, Novell, Red Hat, etc.

</td></tr></tbody></table>

- Set <span class="s1">Edit Mode</span> to <span class="s1">READ\_ONLY</span> or <span class="s1">WRITABLE</span> based on your use case
- Enable periodic sync if needed under <span class="s1">**Sync Settings**</span>
- Save and test the connection

## **Execution**

Once saved, test the login by:

1. Navigating to the Keycloak login page
2. <span class="s1">You will now see </span>**“Login with Google”**<span class="s1">, </span>**“Login with GitHub”**<span class="s1">, etc.</span>
3. Click the button to initiate the external login
4. Upon successful authentication, you will be redirected back to Keycloak with a valid session

You can manage the linked identity in the Keycloak Admin Console under:

```
Users > [user] > Identity Provider Links
```