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 keycloak-connect 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: Variable Description Purpose REALM The realm name from the Keycloak Admin Console Defines the namespace for authentication and authorization AUTH_SERVER_URL The full realm URL from Keycloak (e.g., https://your-domain/realms/xyz ) Used as the OIDC issuer base URL CLIENT_ID Client ID from the Keycloak Clients page Identifies the application in Keycloak CLIENT_SECRET Secret for the OIDC client, found in the Credentials tab of the client Authenticates the Node.js application to Keycloak REDIRECT_URI URI where users are redirected after authentication Ensures Keycloak returns control to your app after login These values can usually be found in the Keycloak Admin Console under Clients and Realm Settings . 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 and install. Verify NPM installation: npm -v Install Required Packages The keycloak-connect 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 keycloak.js and add the following code: 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 ( REALM , AUTH_SERVER_URL , CLIENT_ID , and CLIENT_SECRET ) with actual values from your Keycloak server. Execution Open the terminal or command prompt and navigate to the directory where keycloak.js is saved. Once in the correct directory, run the script with the command: node keycloak.js If the connection is successful: Visit http://localhost:3000 in your browser to access the public route. Visit http://localhost:3000/protected to trigger Keycloak authentication. Upon successful login, you’ll be redirected back and see protected content. Visit http://localhost:3000/logout 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 Flask-OIDC . 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: Variable Description Purpose CLIENT_ID Client ID from the Keycloak Clients page Identifies the Flask app in the Keycloak realm CLIENT_SECRET Secret from the Credentials tab of the client Authenticates the Flask app with Keycloak ISSUER Full Keycloak realm URL (e.g. https://your-domain/realms/your-realm ) Defines the OpenID Connect issuer REDIRECT_URI The callback URL Keycloak will redirect to after login Used by Flask-OIDC to complete login flow TOKEN_ENDPOINT Token URL from Keycloak Used for exchanging authorization codes for access tokens USERINFO_ENDPOINT User info endpoint from Keycloak Used to fetch user profile after login These values can be found in the Keycloak Admin Console under Clients → [Your Client] → Settings / Credentials / Endpoints . 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 and install. Verify pip 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 app.py and add the following code: 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 client_id , client_secret , and URL fields with actual values from your Keycloak instance. Execution Open the terminal and navigate to the directory where app.py is saved. Once in the correct directory, run the script with the command: python3 app.py If the connection is successful: Open http://localhost:5000 in your browser — Public route. Open http://localhost:5000/protected — Redirects to Keycloak login. After logging in, you’ll see user info returned from the protected route. Visit http://localhost:5000/logout 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 jumbojett/openid-connect-php 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: Variable Description Purpose CLIENT_ID Client ID from the Keycloak Admin Console Identifies the PHP app in the Keycloak realm CLIENT_SECRET Secret from the Client > Credentials tab Authenticates the PHP app with Keycloak ISSUER The Keycloak realm URL (e.g., https://your-domain/realms/your-realm ) Acts as the OIDC issuer and discovery endpoint REDIRECT_URI The URI that Keycloak will redirect to after login Where the user will be sent after successful authentication TOKEN_ENDPOINT Token URL under the selected realm Used to retrieve access/ID tokens USERINFO_ENDPOINT URL to fetch user profile information Used to retrieve authenticated user details These values can be copied from the Keycloak Admin Console under Clients > [Your Client] > Endpoints . 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 and follow the install instructions Install Required Package Install the jumbojett/openid-connect-php package using Composer: composer require jumbojett/openid-connect-php Code Once all prerequisites are set up, create a file named keycloak.php and add the following code: 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 "
"; print_r($userInfo); echo ""; ?> Replace: https://your-keycloak-domain/realms/your-realm with your actual realm URL CLIENT_ID and CLIENT_SECRET with credentials from the Keycloak client settings http://localhost:8000/keycloak.php with your desired callback/redirect URI Ensure the Valid Redirect URIs field in Keycloak matches the above redirect URI. Execution Start a PHP development server in the directory containing keycloak.php : php -S localhost:8000 Open your browser and navigate to: http://localhost:8000/keycloak.php If the connection is successful: You’ll be redirected to the Keycloak login page. After authentication, you’ll be redirected back to the PHP script. 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: Variable Description Purpose CLIENT_ID Client ID from the Keycloak Admin Console Identifies the Go app in the Keycloak realm CLIENT_SECRET Secret from the Credentials tab of the client Authenticates the Go app with Keycloak ISSUER_URL Realm URL (e.g., https://your-domain/realms/your-realm ) Base URL for OIDC discovery and validation REDIRECT_URL The callback URL Keycloak redirects to after successful login Required to complete the OIDC flow These values are found under Clients > [Your Client] > Settings / Endpoints 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 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 main.go and add the following code: 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: CLIENT_ID and CLIENT_SECRET with your Keycloak client credentials https://your-keycloak-domain/realms/your-realm with your realm’s base URL http://localhost:8080/callback should be registered in Keycloak’s Valid Redirect URIs Execute Run the application with: go run main.go In your browser, navigate to: http://localhost:8080 You will be redirected to the Keycloak login screen. After logging in: The app will redirect to /callback 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: Variable Description Purpose REALM The name of the Keycloak realm Defines the authentication namespace CLIENT_ID Client ID from the Keycloak Admin Console Identifies the Spring Boot app in Keycloak ISSUER_URI Realm URL (e.g. https://your-domain/realms/your-realm ) Used by Spring Security for token validation JWKS_URI URL to the JWKS endpoint (auto-resolved by Spring from ISSUER_URI) Used to fetch public keys for token signature verification These values can be found in the Keycloak Admin Console → Clients and under the OpenID Connect Endpoints 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 or 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
You have accessed a protected frontend app using Keycloak.