npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2025 – Pkg Stats / Ryan Hefner

keycloak-adapter-api

v2.0.2

Published

Adapter API to integrate Node.js (Express) applications with Keycloak. Provides middleware for authentication, authorization, token validation, and route protection via OpenID Connect.

Readme

🔐 Keycloak Adapter API for Node.js (Express)

An adapter API to seamlessly integrate Node.js Express applications with Keycloak for authentication and authorization using OpenID Connect (OIDC). This middleware provides route protection, token validation, user role management, and easy access to Keycloak-secured APIs. Ideal for securing RESTful services, microservices, and Express-based backends. it is based on 'keycloak-connect', 'express-session' and '@keycloak/keycloak-admin-client'


⚠️ DEPRECATED

-- @Deprecated -- This package is deprecated. For better simplicity and logical separation of functions, it has been divided into two packages:

  • keycloak-express-middleware - An adapter API that seamlessly integrates Node.js Express applications with Keycloak for authentication and authorization using OpenID Connect (OIDC). This middleware provides route protection, token validation, and user role management. It is ideal for securing RESTful services, microservices, Express-based backends, and JavaScript or Express frontends.
  • keycloak-api-manager — A comprehensive Node.js library that wraps the official Keycloak Admin REST API, providing a clean and consistent functional interface for programmatic management of Keycloak resources. With this package, you can easily interact with Keycloak just like through its Admin Console.

📦 Features

  • 🔑 OIDC-based authentication with Keycloak
  • 🧾 Access token validation (JWT)
  • 🔐 Route protection via role-based access control
  • 🔁 Automatic token refresh (optional)
  • ⚙️ Configurable Keycloak client and realm settings
  • 👤 User info extraction from token
  • 🌍 CORS support and integration with frontend apps (SPA or mobile)

🚀 Installation

npm install keycloak-adapter-api

Or, if using Yarn:

yarn add keycloak-adapter-api

🛠️ Get Keycloak Configuration

Copy or Download from keycloak admin page your client configuration keycloak.json by visiting the Keycloak Admin Console → clients (left sidebar) → choose your client → Installation → Format Option → Keycloak OIDC JSON → Download

{
  "realm": "your-realm",
  "auth-server-url": "https://your-keycloak-domain/auth",
  "ssl-required": "external",
  "resource": "your-client-id",
  "credentials": {
    "secret": "your-client-secret"
  },
  "confidential-port": 0
}

📄 Usage Example

const express = require('express');
const keycloackAdapter = require('keycloak-adapter-api');

const app = express();


// Configure and Initialize Keycloak adapter
await keycloackAdapter.configure(app,{
        "realm": "Realm-Project",
        "auth-server-url": "https://YourKeycloakUrl:30040/",
        "ssl-required": "external",
        "resource": "keycloackclientName",
        "credentials": {
            "secret": "aaaaaaaaaa"
        },
        "confidential-port": 0
    },
    {
        session:{
            secret: 'mySecretForSession',
        }
    });


// Public route
app.get('/', (req, res) => {
  res.send('Public route: no authentication required');
});

/* Protected routes (any authenticated user)   */

// Example of login with keycloackAdapter.login function
// After login redirect to "/home" 
app.get('/signIn', (req, res) => {
    console.log("Your Custom Code");
    keycloackAdapter.login(req,res,"/home")

});

// Example of login with keycloackAdapter.loginMiddleware middleware
// After login redirect to "/home" 
app.get('/loginMiddleware', keycloackAdapter.loginMiddleware("/home") ,(req, res) => {
    // Response handled by middleware, this section will never be reached.
});

// Example of logout with keycloackAdapter.logout function
// After login redirect to "http://localhost:3001/home" 
app.get('/logout', (req, res) => {
    console.log("Your Custom Code");
    keycloackAdapter.logout(req,res,"http://localhost:3001/home");
});

// Example of logout with keycloackAdapter.logoutMiddleware middleware
// After login redirect to "http://localhost:3001/home"
app.get('/logoutMiddle', keycloackAdapter.logoutMiddleware("http://redirctUrl"), (req, res) => {
    // Response handled by middleware, this section will never be reached.
});


// Example of protection with keycloackAdapter.protectMiddleware middleware
// Access is allowed only for authenticated users
app.get('/private', keycloackAdapter.protectMiddleware(), (req, res) => {
    console.log("Your Custom Code");
    console.log( req.session);
    res.redirect('/auth');
});

// Example of protection with keycloackAdapter.protectMiddleware middleware
// whith a static client role validation string
// Access is allowed only for authenticated admin users
app.get('/privateStaticClientRole', keycloackAdapter.protectMiddleware("admin"), (req, res) => {
    // "Your Custom Code"
    res.send("Is its admin.");
});

// Example of protection with keycloackAdapter.protectMiddleware middleware
// whith a static realm role validation string
// Access is allowed only for authenticated realm admin users
app.get('/privateStaticRealmRole', keycloackAdapter.protectMiddleware("realm:admin"), (req, res) => {
    // "Your Custom Code"
    res.send("Is its admin realm:admin.");
});

// Example of protection with keycloackAdapter.protectMiddleware middleware
// whith a static other client role validation string
// Access is allowed only for authenticated otherClient admin users
app.get('/privateStaticRealmRole', keycloackAdapter.protectMiddleware("otherClient:admin"), (req, res) => {
    // "Your Custom Code"
    res.send("Is its admin otherClient:admin.");
});

// Example of protection with keycloackAdapter.protectMiddleware middleware
// whith a control function tmpFunction
// Access is allowed only for authenticated admin users
let tmpFunction=function (token, req) {
    return token.hasRole('admin');
}
app.get('/isAdmin', keycloackAdapter.protectMiddleware(tmpFunction), (req, res) => {
    // "Your Custom Code"
    res.send("Is its admin tmpFunction.");
});


// Example of protection with keycloackAdapter.customProtectMiddleware middleware
// whith a control function tmpFunctionString
// Access is allowed only for authenticated users with role defined by tmpFunctionString
let tmpFunctionString=function (req,res) {
    let id=req.params.id
    // Control String by url param Id 
    return (`${id}`);
}
app.get('/:id/isAdmin', keycloackAdapter.customProtectMiddleware(tmpFunctionString), (req, res) => {
    // "Your Custom Code"
    res.send("Is its admin tmpFunctionString.");
});


// Example of protection with keycloackAdapter.encodeTokenRole middleware
// Encode the token and add it to req.encodedTokenRole
// Use req.encodedTokenRole.hasRole("role") to check whether the token has that role or not
app.get('/encodeToken', keycloackAdapter.encodeTokenRole(), (req, res) => {
    if(req.encodedTokenRole.hasRole('realm:admin'))
        res.send("Is its a realm admin");
    else
        res.send("Is its'n a realm admin");

});

// This section provides examples of how to protect resources based on permissions
// rather than roles.

// Example of protection with keycloackAdapter.enforcerMiddleware middleware
// whith a static control string
// Access is allowed only for users with 'ui-admin-resource' permission defined 
// in keycloak
app.get('/adminResource', keycloackAdapter.enforcerMiddleware('ui-admin-resource'), (req, res) => {
    // If this section is reached, the user has the required privileges; 
    // otherwise, the middleware responds with a 403 Access Denied.
    res.send('You are an authorized ui-admin-resource User');
});

// Example of protection with keycloackAdapter.enforcerMiddleware middleware
// whith a control function tmpFunctionEnforceValidation
// Access is allowed only for users with 'ui-admin-resource' or
// ui-viewer-resource permission defined in keycloak
let tmpFunctionEnforceValidation=function (token,req,callback) {
    // Check permission using token.hasPermission, which performs the verification
    // and responds with a callback that returns true if the permission is valid, 
    // and false otherwise.
    if(token.hasPermission('ui-admin-resource',function(permission){
        if(permission) callback(true);
        else if(token.hasPermission('ui-viewer-resource',function(permission){
            if(permission) callback(true);
            else callback(false);
        }));
    }));
}
app.get('/adminOrViewerResorce', keycloackAdapter.enforcerMiddleware(tmpFunctionEnforceValidation), (req, res) => {
    // If this section is reached, the user has the required privileges 
    // driven by tmpFunctionEnforceValidation; otherwise, the middleware responds
    // with a 403 Access Denied.
    res.send('You are an authorized User');
});


// Example of protection with keycloackAdapter.customEnforcerMiddleware middleware
// whith a control function tmpFunctionEnforce that define the control string
// Access is allowed only for users with a url params ':permission' permission defined 
// in keycloak
let tmpFunctionEnforce=function (req,res) {
    // Permission that depends on a URL parameter.
    return(req.params.permission);
}
app.get('/urlParameterPermission/:permission', keycloackAdapter.customEnforcerMiddleware(tmpFunctionEnforce), (req, res) => {
    res.send(`You are an authorized User with ${req.params.permission} permission`);
});

// Example of protection with keycloackAdapter.encodeTokenPermission middleware
// Encode the token permission and add it to req.encodedTokenPremission
// Use req.encodedTokenPremission.hasPermission("permission") to check whether
// the token has that permission or not
app.get('/encodeTokenPermission', keycloackAdapter.encodeTokenPermission(), (req, res) => {
    // Check permission using token.hasPermission, which performs the verification
    // and responds with a callback that returns true if the permission is valid, 
    // and false otherwise.
    req.encodedTokenPremission.hasPermission('ui-admin-resource', function(permission){
        if(permission)
            res.send('You are an authorized User by ui-admin-resource permission');
        else res.status(403).send("access Denied");
    });
});



// Start the server
const PORT = process.env.PORT || 3000;
app.listen(PORT, () => {
  console.log(`Server running at http://localhost:${PORT}`);
});

🧩 Configuration

In your Express application:

import keycloakAdapter from 'keycloak-adapter-api';

// Configure and Initialize Keycloak adapter
keycloackAdapter.configure(app,{
        "realm": "Realm-Project",
        "auth-server-url": "https://YourKeycloakUrl:30040/",
        "ssl-required": "external",
        "resource": "keycloackclientName",
        "credentials": {
            "secret": "aaaaaaaaaa"
        },
        "confidential-port": 0
    },
    {
        session:{
            secret: 'mySecretForSession',
        }
    })

keycloackAdapter.configure is a configuration function for the Keycloak adapter in an Express application.
It must be called at app startup, before defining any protected routes. It is an async function and returns a promise

Parameters:

  • app: Express application instance (e.g., const app = express();)
  • keyCloakConfig: JSON object containing the Keycloak client configuration. This can be obtained from the Keycloak admin console: Clients → [client name] → Installation → "Keycloak OIDC JSON" → Download Example: { "realm": "realm-name", "auth-server-url": "https://keycloak.example.com/", "ssl-required": "external", "resource": "client-name", "credentials": { "secret": "secret-code" }, "confidential-port": 0 }
  • keyCloakOptions: advanced configuration options for the adapter. Main supported options:
    • session: Express session configuration (as in express-session)
    • scope: authentication scopes (e.g., 'openid profile email offline_access') Note: to use offline_access, the client must have the option enabled and the user must have the offline_access role.
    • idpHint: to suggest an identity provider to Keycloak during login
    • cookies: to enable cookie handling
    • realmUrl: to override the realm URL
  • adminClientCredentials: [Optional] Advanced configuration for setting up the realm-admin user or client, which will be used as the administrator to manage Keycloak via API. This is required in order to use the administrative functions exposed by this library. If this parameter is not provided, it will not be possible to use the administrative functions of Keycloak exposed by this adapter. In fact, exports.kcAdminClient will be null, so any attempt to call keycloakAdapter.kcAdminClient will result in a runtime error due to access on an undefined object Main supported options:
    • realmName: [Optional] A String that specifies the realm to authenticate against, if different from the "keyCloakConfig.realm" parameter. If you intend to use Keycloak administrator credentials, this should be set to 'master'.
    • scope: [Optional] A string that specifies The OAuth2 scope requested during authentication (optional). Typically, not required for administrative clients. example:openid profile
    • requestOptions: [Optional] JSON parameters to configure HTTP requests (such as custom headers, timeouts, etc.). It is compatible with the Fetch API standard. Fetch request options https://developer.mozilla.org/en-US/docs/Web/API/fetch#options
    • username: [Optional] string username. Required when using the password grant type.
    • password: [Optional] string password. Required when using the password grant type.
    • grantType: The OAuth2 grant type used for authentication. Possible values: 'password', 'client_credentials', 'refresh_token', etc.
    • clientId: string containing the client ID configured in Keycloak. Required for all grant types.
    • clientSecret: [Optional] string containing the client secret of the client. Required for client_credentials or confidential clients.
    • totp: string for Time-based One-Time Password (TOTP) for multifactor authentication (MFA), if enabled for the user.
    • offlineToken: [Optional] boolean value. If true, requests an offline token (used for long-lived refresh tokens). Default is false.
    • refreshToken: [Optional] string containing a valid refresh token to request a new access token when using the refresh_token grant type.

🔧 Available Middlewares

underKeycloakProtection(callback) - deprecated -

@deprecated. Use the configure Method with await keycloakAdapter.configure(...), then define your resources as you normally would in Express:

    await keycloakAdapter.configure(config_Parameters);
    
    // all your routes

    app.get('/my-route', handler);

Alternatively, if you prefer to define your resources inside a container after configuration, you can use the then syntax:

    keycloakAdapter.configure(configParameters).then(() => {
        // Define all your routes here
        app.get('/my-route', handler);
    });

This Method is deprecated and will be removed in future versions.

Method to define Express routes that must be protected by Keycloak.

This method must be called after Keycloak has been configured with configure(). The routes declared inside the provided callback will be protected and will have access to authentication/authorization features managed by Keycloak.

📌 Public (unprotected) routes should be declared before calling this method.

@param {Function} callback - A function that defines all routes to be protected. It must contain exclusively routes requiring authentication.

✅ Usage example:

// Public route not protected by Keycloak
app.get('/public', (req, res) => {
res.send('Public content');
});

// Section of routes protected by Keycloak
keycloakAdapter.underKeycloakProtection(() => {

    // This function is deprecated and will be removed in future versions. 
    // It is retained only for backward compatibility with older versions
    
    // Route protected by authentication
    app.get('/confidential', keycloakAdapter.protectMiddleware(), (req, res) => {
        res.send('Confidential content visible only to authenticated users');
    });

    // Route with forced login: handled directly by middleware
    app.get('/loginMiddleware', keycloakAdapter.loginMiddleware("/home"), (req, res) => {
        // This response will never be sent because the middleware handles the 
        // request directly
    });
});

protectMiddleware([conditions])

Middleware to protect Express routes based on authentication and, optionally, authorization via Keycloak roles.

Allows restricting access to a resource only to authenticated users or to those possessing specific roles in the realm or in a Keycloak client.

@param {string|function} [conditions]

  • If a string, specifies one or more required roles, using the syntax:
    • 'role' → client role in the configured client (e.g., 'admin')

    • 'clientid:role' → client role of a specific client (e.g., 'myclient:editor')

    • 'realm:role' → realm role (e.g., 'realm:superuser')

    • If a function, receives (token, req) and must return true or false synchronously. This function enables custom authorization logic.

      • The token object passed to the authorization function exposes methods such as:
        • token.hasRole('admin') // client role in configured client
        • token.hasRole('realm:superuser') // realm role
        • token.hasRole('my-client:editor') // client role of a specific client
        • token.hasResourceRole('editor', 'my-client-id') // equivalent to hasRole('my-client:editor')

      The authorization function must be synchronous and return true (allow access) or false (deny access).

@returns {Function} Express middleware to protect the route.

✅ Usage example:


// Authentication only, no role check
app.get('/admin', keycloakAdapter.protectMiddleware(), (req, res) => {
    res.send('Only authenticated users can see this resource.');
});

// Check on client role of configured client (e.g., 'admin')
app.get('/admin', keycloakAdapter.protectMiddleware('admin'), (req, res) => {
    res.send('Only users with the admin client role can access.');
});

// Check on role of a specific client (e.g., client 'clientid', role 'admin')
app.get('/admin', keycloakAdapter.protectMiddleware('clientid:admin'), (req, res) => {
    res.send('Only users with admin role in client "clientid" can access.');
});

// Check on realm role (e.g., 'superuser' role at realm level)
app.get('/admin', keycloakAdapter.protectMiddleware('realm:superuser'), (req, res) => {
    res.send('Only users with realm superuser role can access.');
});

// Custom synchronous authorization function
app.get('/custom', keycloakAdapter.protectMiddleware((token, req) => {
    // Allow only if user has realm role 'editor'
    // and the request has a specific custom header
    return token.hasRealmRole('editor') && req.headers['x-custom-header'] === 'OK';
}), (req, res) => {
    res.send('Access granted by custom authorization function.');
});

customProtectMiddleware(fn)

Middleware similar to protectMiddleware but with dynamic role checking via a function.

Unlike protectMiddleware, which accepts a string expressing the role or a control function that works on the token, this middleware accepts a function that receives the Express request and response objects req and res and must return a string representing the role control string.

This is useful for parametric resources where the role control string must be dynamically generated based on the request, for example, based on URL parameters or query strings.

Note: this function does not access or parse the token, nor performs any checks other than the role, so it cannot be used for complex logic depending on request properties other than the role (e.g., client IP, custom headers, etc.). The function's sole task is to generate the role control string.

--- Parameters ---

@param {function} customFunction - function that receives (req, res) and returns a string with the role control string to pass to Keycloak.

✅ Usage example:


app.get('/custom/:id', keycloakAdapter.customProtectMiddleware((req) => {
    // Dynamically builds the client role based on URL parameter 'id'
    return `clientRole${req.params.id}`;
}), (req, res) => {
    res.send(`Access granted to users with role 'clientRole${req.params.id}'`);
});

enforcerMiddleware(conditions, options)

enforcerMiddleware is a middleware to enable permission checks based on resources and policies defined in Keycloak Authorization Services (UMA 2.0-based).

Unlike protectMiddleware and similar, which only verify authentication or roles, enforcerMiddleware allows checking if the user has permission to access a specific protected resource through flexible and dynamic policies.

Useful in contexts where resources are registered in Keycloak (such as documents, instances, dynamic entities) and protected by flexible policies.

--- Parameters ---

@param {string|function} conditions

  • string containing the name of the resource or permission to check
  • custom check function with signature: function(token, req, callback)
    • token: decoded Keycloak token
    • req: Express request
    • callback(boolean): invoke with true if authorized, false otherwise

@param {object} [options] (optional)

  • response_mode: 'permissions' (default) or 'token'
  • claims: object with claim info for dynamic policies (e.g. owner id matching)
  • resource_server_id: resource client id (default: current client)

--- How it works ---

  • If conditions is a function, it is used for custom checks with callback.
  • If conditions is a string, keycloak.enforcer(conditions, options) is used for the check.

--- response_mode modes ---

  1. 'permissions' (default)

    • Keycloak returns the list of granted permissions (no new token)
    • Permissions available in req.permissions
  2. 'token'

    • Keycloak issues a new access token containing the granted permissions
    • Permissions available in req.kauth.grant.access_token.content.authorization.permissions
    • Useful for apps with sessions and decision caching

--- Keycloak requirements ---

The client must have:

  • Authorization Enabled = ON
  • Policy Enforcement Mode = Enforcing
  • Add permissions to access token = ON

You must also configure in Keycloak:

  • Resources
  • Policies (e.g., role, owner, JS script)
  • Permissions (associate policies to resources)

✅ Usage example:


// Check with static string
app.get('/onlyAdminroute', keycloakAdapter.enforcerMiddleware('ui-admin-resource'), (req, res) => {
    res.send('You are an authorized admin for this resource');
});

// Check with custom function (async with callback)
app.get('/onlyAdminrouteByfunction', keycloakAdapter.enforcerMiddleware(function(token, req, callback) {
    token.hasPermission('ui-admin-resource', function(permission) {
        if (permission) callback(true);
        else {
            token.hasPermission('ui-viewer-resource', function(permission) {
                callback(permission ? true : false);
            });
        }
    });
}), (req, res) => {
    res.send('You are an authorized admin or viewer (custom check)');
});

customEnforcerMiddleware(fn, options)

customEnforcerMiddleware is a middleware for permission checks based on resources and policies defined in Keycloak Authorization Services (UMA 2.0), using dynamic permission strings.

This middleware is similar to enforcerMiddleware, but takes a function customFunction(req, res) as a parameter, which must dynamically return the permission/resource string to be checked.

--- Parameters ---

@param {function} customFunction Function that receives req and res and returns the control string for Keycloak. Example:

function customFunction(req, res) {
    // Your function logic
    return req.params.permission;
}

@param {object} [options] (optional) Additional options passed to keycloak.enforcer(), including: - response_mode: 'permissions' (default) or 'token' - claims: object with claim info for dynamic policies (e.g., owner ID) - resource_server_id: string representing the resource client ID (default: current client)

--- response_mode options ---

  1. 'permissions' (default)

    • The server returns only the list of granted permissions (no new token)
    • Permissions available in req.permissions
  2. 'token'

    • The server issues a new access token with granted permissions
    • Permissions available in req.kauth.grant.access_token.content.authorization.permissions
    • Useful for decision caching, session handling, automatic token refresh

--- Keycloak Requirements ---

The client must be configured with:

  • Authorization Enabled = ON
  • Policy Enforcement Mode = Enforcing
  • Add permissions to access token = ON

You must also have created:

  • Resources
  • Policies (e.g., role, owner, JS rules)
  • Permissions (linking policies to resources)

✅ Usage example:


const tmpFunctionEnforce = function(req, res) {
    return req.params.permission; // dynamic permission from URL parameter
};

app.get('/onlyAdminrouteByfunction/:permission', keycloakAdapter.customEnforcerMiddleware(tmpFunctionEnforce), (req, res) => {
    res.send('You are an authorized user with dynamic permission: ' + req.params.permission);
});

encodeTokenRole()

encodeTokenRole is a middleware that decodes the Keycloak token and adds it to the Express request as req.encodedTokenRole.

Unlike protectMiddleware or customProtectMiddleware, this middleware does NOT perform any role or authentication checks, but simply extracts and makes the decoded token available within the route handler function.

It is especially useful when you want to perform custom logic based on roles or other information contained in the token directly in the route handler, for example showing different content based on role.

--- Contents of req.encodedTokenRole ---

Represents the decoded Keycloak token and exposes several useful methods such as:

  • token.hasRole('admin') // true/false if it has client role "admin"
  • token.hasRole('realm:superuser') // true/false if it has realm role "superuser"
  • token.hasRole('my-client:editor') // true/false if it has client role "editor" for client "my-client"
  • token.hasResourceRole('editor', 'my-client-id') // identical to hasRole('my-client:editor')

✅ Usage example:


app.get('/encodeToken', keycloakAdapter.encodeTokenRole(), (req, res) => {
    if (req.encodedTokenRole.hasRole('realm:admin')) {
        res.send("User with admin (realm) role in encodeToken");
    } else {
        res.send("Regular user in encodeToken");
    }
});

encodeTokenPermission()

encodeTokenPermission ia s Middleware whose sole purpose is to decode the access token present in the request and add to the req object a property called encodedTokenPermission containing the token's permissions.

Unlike enforcerMiddleware and customEnforcerMiddleware, it does not perform any access or authorization checks, but exposes a useful method (hasPermission) for checking permissions within the route handler.

It is particularly useful when:

  • you want to customize the response based on the user's permissions (e.g., show a different page),
  • you want to manually handle access or perform custom checks on multiple permissions,
  • you do not want to block access upfront but decide dynamically within the route handler.

--- Additions to req ---

After applying the middleware, req contains:

  • @property {Object} req.encodedTokenPermission An object exposing the method:
    • hasPermission(permission: string, callback: function(boolean)) Checks whether the token contains the specified permission. The callback receives true if the permission is present, false otherwise.

✅ Usage example:


app.get('/encodeTokenPermission',
    keycloakAdapter.encodeTokenPermission(),
    (req, res) => {
        req.encodedTokenPermission.hasPermission('ui-admin-resource', function(perm) {
            if (perm)
                res.send('You are an authorized admin user by function permission parameters');
            else
                res.status(403).send('Access Denied by encodeTokenPermission');
        });
    });

loginMiddleware(redirectTo)

loginMiddleware is a Middleware used to force user authentication via Keycloak.

It is particularly useful when you want to:

  • ensure the user is authenticated,
  • redirect the user to a specific page after login or when access is denied,
  • integrate automatic login flows on routes that don’t require direct authorization, but where login should still be enforced (e.g., profile page, personal area, etc.).

--- Behavior ---

  1. If the user is not authenticated, Keycloak redirects them to the login flow.
  2. If authentication fails or is denied, the user is redirected according to Keycloak's configured settings.
  3. If authentication is successful, the user is redirected to 'redirectTo' (usually /home, /dashboard, etc.).

--- Parameters ---

@param {string} redirectTo - URL to redirect the user to after login.

--- Warning ---

The route handler callback is never executed, because the middleware will respond earlier with a redirect or block the request.

✅ Usage example:


app.get('/loginMiddleware', keycloakAdapter.loginMiddleware("/home"), (req, res) => {
        // This section is never reached
        res.send("If you see this message, something went wrong.");
});

logoutMiddleware(redirectTo)

logoutMiddleware Middleware is used to force user logout, removing the local session and redirecting the user to Keycloak's logout endpoint according to its configuration.

It is useful when:

  • You want to completely log out the user,
  • You want to terminate the session on Keycloak (not just locally),
  • You want to redirect the user to a public page, such as a homepage, after logout.

--- Behavior ---

  1. Retrieves the id_token of the authenticated user.
  2. Constructs the Keycloak logout URL including the token and the redirect URL.
  3. Destroys the local Express session (e.g., cookies, user data).
  4. Redirects the user to the Keycloak logout URL, which in turn redirects to the provided URL.

--- Parameters ---

@param {string} redirectTo - URL to which the user will be redirected after complete logout.

✅ Usage example:


app.get('/logoutMiddleware', keycloakAdapter.logoutMiddleware("http://localhost:3001/home"),  (req, res) => {
        // This section is never reached
        // The middleware handles logout and redirection automatically
    });

--- Note ---

  • The middleware never executes the route callback, as it fully handles the response.
  • The redirectTo parameter must match a valid redirect URI configured in Keycloak for the client.

--- Requirements ---

  • The Keycloak client must have properly configured Valid Redirect URIs.
  • The Express session must be active (e.g., express-session properly initialized).

🔧 Available Functions

login(req, res, redirectTo)

login Function not a middleware, but a classic synchronous function that forces user authentication via Keycloak and, if the user is not authenticated, redirects them to the login page. After successful login, the user is redirected to the URL specified in the redirectTo parameter.

--- Differences from loginMiddleware ---

  • loginMiddleware handles everything automatically before the route handler function.
  • login instead is a function that can be manually called inside the route handler, offering greater control over when and how login is enforced.

--- Parameters ---

  • @param {Object} req - Express Request object
  • @param {Object} res - Express Response object
  • @param {string} redirectTo - URL to redirect the user to after successful login

--- Behavior ---

  1. Attempts to protect the request using keycloak.protect().
  2. If the user is authenticated, it performs res.redirect(redirectTo).
  3. If not authenticated, Keycloak automatically handles redirection to the login page.

✅ Usage example:


app.get('/login', (req, res) => {
    // Your route logic
    // ...
    // Force authentication if necessary
    keycloakAdapter.login(req, res, "/home");
});

--- Notes ---

  • The function can be called within an Express route, allowing for custom conditional logic.
  • Useful for scenarios where only certain conditions should trigger a login.

--- Requirements ---

  • Valid Redirect URIs must include the URL passed to redirectTo.

logout(req, res, redirectTo)

logout Function is not a middleware, but a classic synchronous function that forces the user to logout via Keycloak. In addition to terminating the current session (if any), it generates the Keycloak logout URL and redirects the user's browser to that address.

--- Differences from logoutMiddleware ---

  • logoutMiddleware is designed to be used directly as middleware in the route definition.
  • logout instead is a function to be called inside the route, useful for handling logout conditionally or within more complex logic.

--- Parameters ---

  • @param {Object} req - Express Request object
  • @param {Object} res - Express Response object
  • @param {string} redirectTo - URL to redirect the user after logout

--- Behavior ---

  1. Retrieves the id_token from the current user's Keycloak token (if present).
  2. Builds the logout URL using keycloak.logoutUrl().
  3. Destroys the user's Express session.
  4. Redirects the user to the Keycloak logout URL, which in turn redirects to redirectTo.

✅ Usage example:


app.get('/logout', (req, res) => {
    // Any custom logic before logout
    // ...
    keycloakAdapter.logout(req, res, "http://localhost:3001/home");
});

--- Requirements ---

  • The user must be authenticated with Keycloak and have a valid token in req.kauth.grant.
  • The URL specified in redirectTo must be present in the Valid Redirect URIs in the Keycloak client.

🔧 Admin Functions

All administrative functions that rely on Keycloak's Admin API must be invoked using the keycloakAdapter.kcAdminClient.{entity}.{function} pattern.

  • {entyty} represents the type of resource you want to manage (e.g., users, roles, groups, clients).
  • {function} is the specific operation you want to perform on that resource (e.g., find, create, update, del). For example:
// get all users of this client
// users is the entity you want to administer.
// find is the method used to retrieve the list of users.
 keycloakAdapter.kcAdminClient.users.find();

Credits to @keycloak/keycloak-admin-client. This admin function is built on top of it. For more details, please refer to the official repository.

entity realm

The realms property provides access to all administrative operations related to Keycloak realms. A realm in Keycloak is a fundamental concept that acts as an isolated tenant: ach realm manages its own set of users, roles, groups, and clients independently.

entity realm functions

function create(realm-dictionary)

create is a method used to create a new realm. This method accepts a realm representation object containing details such as is, name @parameters:

  • realm-dictionary: is a JSON object that accepts filter parameters
    • id:[required] The internal ID of the realm. If omitted, Keycloak uses the realm name as the ID.
    • realm:[required] The name of the realm to create.
    • Additional optional properties can be passed to configure the realm (e.g., enabled, displayName, etc.).
 // create a new realm
 const realm = await keycloakAdapter.kcAdminClient.realms.create({
     id: "realm-id",
     realm: "realmName",
 });
function update(filter,realm-dictionary)

Updates the configuration of an existing realm. You can use this method to modify settings such as login behavior, themes, token lifespans, and more. @parameters:

  • filter:is a JSON object that accepts filter parameters
    • realm:[required] The identifier of the realm you want to update.
  • realm-dictionary: An object containing the updated realm configuration. Only the fields you want to change need to be included.
    • realm properties that can be passed to update the realm (e.g., enabled, displayName, etc.).
 // update a realm
 await keycloakAdapter.kcAdminClient.realms.update(
     { realm: 'realm-name' },
     {
         displayName: "test",
     }
 );
function del(filter)

Deletes a specific realm from the Keycloak server. This operation is irreversible and removes all users, clients, roles, groups, and settings associated with the realm. @parameters:

  • filter: is a JSON object that accepts filter parameters
    • realm:[required] The name of the realm to delete.
 // delete 'realmeName' realm
 const realm = await keycloakAdapter.kcAdminClient.realms.del({
     realm: "realmName",
 });
function find(filter)

Retrieves a list of all realms configured in the Keycloak server. This includes basic metadata for each realm such as ID and display name, but not the full configuration details. This method does not take any parameters.

 // delete 'realmeName' realm
 const realms = await keycloakAdapter.kcAdminClient.realms.find();
console.log("Retrieved realms:",realms);
function findOne(filter)

Retrieves the full configuration and metadata of a specific realm by its name (realm ID). This includes settings like login policies, themes, password policies, etc. @parameters:

  • filter: is a JSON object that accepts filter parameters
    • realm:[required] The name (ID) of the realm you want to retrieve.
 // delete 'realmeName' realm
 const realmConfig = await keycloakAdapter.kcAdminClient.realms.findOne({
     realm: "realmName",
 });
console.log("Retrieved realm:",realmConfig);
function partialImport(configuration)

Performs a partial import of realm configuration into a Keycloak realm. This allows you to import users, roles, groups, clients, and other components without replacing the entire realm. It’s useful for incremental updates or merging configuration pieces. @parameters:

  • configuration: is a JSON object that accepts filter parameters
    • realm:[required] The name of the realm where the data should be imported.
    • representation:[required] A JSON object representing part of the realm configuration to be imported(can include users, roles, groups, clients, etc.).
      • ifResourceExists:[required] Defines the behavior when an imported resource already exists in the target realm. Options are:
        • 'FAIL' – the operation fails if a resource already exists.
        • 'SKIP' – existing resources are skipped.
        • 'OVERWRITE' – existing resources are overwritten.
      • other configuration to be imported like users, roles, groups ...
 // import configuration
const roleToImport: PartialImportRealmRepresentation = {
    ifResourceExists: "FAIL",
    roles: {
        realm: [
            {
                id: "9d2638c8-4c62-4c42-90ea-5f3c836d0cc8",
                name: "myRole",
                scopeParamRequired: false,
                composite: false,
            },
        ],
    },
};
// partial realm import 
const result = await keycloakAdapter.kcAdminClient.realms.partialImport({
    realm: 'my-realm',
    rep: roleToImport,
});
function export(configuration)

Exports the configuration of a specific realm. This method returns the full realm representation in JSON format, including roles, users, clients, groups, and other components depending on the provided options. @parameters:

  • configuration: is a JSON object that accepts filter parameters
    • realm:[required] The name of the realm to export.
    • exportClients: [optional] boolean, Whether to include clients in the export. Default: true.
    • exportGroupsAndRoles: [optional] boolean, Whether to include groups and roles in the export. Default: true.
 
//  realm export 
const exportedRealm = await keycloakAdapter.kcAdminClient.realms.export({
    realm: 'my-realm',
    exportClients: true,      // optional
    exportGroupsAndRoles: true, // optional
});
// print exportedRealm
console.log(JSON.stringify(exportedRealm, null, 2));
function getClientRegistrationPolicyProviders(configuration)

Fetches the list of available client registration policy providers for the specified realm. These providers define how new clients can be registered and what rules or validations apply (e.g., allowed scopes, required attributes). @parameters:

  • configuration: is a JSON object that accepts filter parameters
    • realm:[required] The name of the realm where you want to list client registration policy providers.
 
//  get Client Registration Policy Providers
await keycloakAdapter.kcAdminClient.realms.getClientRegistrationPolicyProviders({
    realm: currentRealmName,
});
function createClientsInitialAccess(realmFilter,options)

Creates a new Initial Access Token for dynamic client registration. This token allows clients to register themselves with the realm using the Dynamic Client Registration API. Useful when you want to allow programmatic client creation in a controlled way. @parameters:

  • realmFilter: is a JSON object that accepts filter parameters
    • realm:[required] The name of the realm where the initial access token should be created.
  • options: is a JSON object that accepts filter parameters
    • count [required] Number of times this token can be used to register new clients.

    • expiration [required] Time (in seconds) after which the token expires. 0 is unlimited

@return - Returns an object containing:

  • id: internal ID of the token
  • token: the actual token string to be used during dynamic registration
  • timestamp: Creation timestamp
  • expiration: Expiration time in seconds
  • count: Maximum allowed uses
  • remainingCount: How many uses are left
//  get Client Registration Policy Providers with oount=1 and unlimited expiration time
const initialAccess= await keycloakAdapter.kcAdminClient.realms.realms.createClientsInitialAccess(
    { realm: currentRealmName },
    { count: 1, expiration: 0 },
);

console.log("Initial Access Token:", initialAccess.token);
function getClientsInitialAccess(realmFilter)

Retrieves all existing Initial Access Tokens for dynamic client registration in a given realm. These tokens are used to allow programmatic or automated registration of clients via the Dynamic Client Registration API. @parameters:

  • realmFilter: is a JSON object that accepts filter parameters
    • realm:[required] The name of the realm from which to list all initial access tokens.

@return - An array of objects representing each initial access token. Each object contains:

  • id: internal ID of the token
  • token: the actual token string to be used during dynamic registration
  • timestamp: Creation timestamp
  • expiration: Expiration time in seconds
  • count: Maximum allowed uses
  • remainingCount: How many uses are left
//  get get Clients Initial Access list
const tokens= await keycloakAdapter.kcAdminClient.realms.getClientsInitialAccess({ realm:'realm-id'});
console.log("Initial Access Tokens:", tokens);
function delClientsInitialAccess(realmFilter)

Deletes a specific Initial Access Token used for dynamic client registration in a given realm. This revokes the token, preventing any future use. @parameters:

  • realmFilter: is a JSON object that accepts filter parameters
    • realm:[required] The name of the realm where the token was created.
    • id:[required] The ID of the initial access token you want to delete.
//  delete Clients Initial Access
await keycloakAdapter.kcAdminClient.realms.delClientsInitialAccess({
    realm: 'realm-id',
    id: 'initial-access-token-id',
});
function addDefaultGroup(realmFilter)

Adds an existing group to the list of default groups for a given realm. Users created in this realm will automatically be added to all default groups. @parameters:

  • realmFilter: is a JSON object that accepts filter parameters
    • realm:[required] The name of the realm where the default group will be set.
    • id:[required] The ID of the group to be added as a default group
//  get get Clients Initial Access list
await keycloakAdapter.kcAdminClient.realms.addDefaultGroup({
    realm: 'realm-id',
    id: 'default-group-id',
});
function removeDefaultGroup(realmFilter)

Removes a group from the list of default groups in a realm. Default groups are automatically assigned to new users when they are created. @parameters:

  • realmFilter: is a JSON object that accepts filter parameters
    • realm:[required] The name of the realm from which to remove the default group.
    • id:[required] The ID of the group you want to remove from the default list.
//  remove from 'realm-id' the group 'default-group-id'
await keycloakAdapter.kcAdminClient.realms.removeDefaultGroup({
    realm: 'realm-id',
    id: 'default-group-id',
});
function getDefaultGroups(realmFilter)

Retrieves a list of all default groups for a specified realm. These are the groups that new users will automatically be added to upon creation. @parameters:

  • realmFilter: is a JSON object that accepts filter parameters
    • realm:[required] The name of the realm from which to retrieve default groups.
//  get 'realm-id' default groups
const defaultGroups = await keycloakAdapter.kcAdminClient.realms.getDefaultGroups({
    realm: 'realm-id',
});
console.log(defaultGroups);
function getGroupByPath(realmFilter)

Retrieves a group object by specifying its hierarchical path in a realm. This is useful when you know the group’s full path (e.g., /parent/child) but not its ID. @parameters:

  • realmFilter: is a JSON object that accepts filter parameters
    • realm:[required] The name of the realm where the group is located.

    • path:[required] TThe full hierarchical path to the group, starting with a slash (/). For example: /developers/frontend.

//  get 'realm-id' group by Path
const defaultGroups = await keycloakAdapter.kcAdminClient.realms.getGroupByPath({
    realm: 'realm-id',
    path: 'realm-name-path'
});
console.log(defaultGroups);
function getConfigEvents(realmFilter)

Retrieves the event configuration settings for a specific realm. This includes settings related to the event listeners, enabled event types, admin events, and more. Useful for auditing and tracking activities inside Keycloak. @parameters:

  • realmFilter: is a JSON object that accepts filter parameters
    • realm:[required] The name of the realm from which to retrieve the event configuration.
//  get Config Events
const config= await keycloakAdapter.kcAdminClient.realms.getConfigEvents({
    realm: 'realm-id',
});
console.log(config);
/* config example:
{
  eventsEnabled: true,
  eventsListeners: ['jboss-logging'],
  enabledEventTypes: ['LOGIN', 'LOGOUT', 'REGISTER'],
  adminEventsEnabled: true,
  adminEventsDetailsEnabled: false
}
*/
function updateConfigEvents(realmFilter,configurationEvents)

Updates the event configuration for a given realm. This includes enabling/disabling events, setting specific event types to track, enabling admin event logging, and choosing which event listeners to use. @parameters:

  • realmFilter: is a JSON object that accepts filter parameters
    • realm:[required] The name of the realm where the configuration will be updated.
  • configurationEvents:is a config events JSON object dictionary like this:
    • eventsEnabled: Enables or disables event logging.
    • eventsListeners: List of event listener IDs to use (e.g., ["jboss-logging"]).
    • enabledEventTypes: List of event types to track (e.g., ["LOGIN", "LOGOUT", "REGISTER"]).
    • adminEventsEnabled: Enables logging for admin events.
    • adminEventsDetailsEnabled: Includes full details in admin event logs if set to true.
//  Update Config Events
const config= await keycloakAdapter.kcAdminClient.realms.updateConfigEvents(
    { realm: 'realm-id'},
    {
        eventsEnabled: true,
        eventsListeners: ['jboss-logging'],
        enabledEventTypes: ['LOGIN', 'LOGOUT', 'UPDATE_PASSWORD'],
        adminEventsEnabled: true,
        adminEventsDetailsEnabled: true,
    });
function findEvents(realmFilter)

Retrieves a list of events that occurred in a specified realm. You can filter the results by event type, user, date range, and other criteria. Useful for auditing login, logout, and other user-related activities. @parameters:

  • realmFilter: is a JSON object that accepts filter parameters
    • realm: [required] The name of the realm to fetch events from.
    • client: [optional] Client ID to filter events for a specific client.
    • type: [optional] Event type to filter (e.g., LOGIN, REGISTER).
    • user: [optional] User ID to filter events related to a specific user.
    • dateFrom: [optional] Start date in ISO 8601 format to filter events.
    • dateTo: [optional] End date in ISO 8601 format to filter events.
    • first: [optional] Pagination offset.
    • max: [optional] Maximum number of events to return.

//  find 10 realm-id events with a type=LOGIN and dateFrom and dateTo. 
const config= await keycloakAdapter.kcAdminClient.realms.findEvents({ 
    realm: 'realm-id',
    type: 'LOGIN',
    dateFrom: '2025-08-01T00:00:00Z',
    dateTo: '2025-08-06T23:59:59Z',
    max: 10
});
function findAdminEvents(realmFilter)

Retrieves administrative events that occurred in a specific realm. Admin events are triggered by actions such as creating users, updating roles, or modifying realm settings. This is useful for auditing changes made via the admin API or admin console. @parameters:

  • realmFilter: is a JSON object that accepts filter parameters
    • realm: [required] The name of the realm to retrieve admin events from.
    • authClient: [optional] Client ID used to perform the action.
    • authIpAddress: [optional] IP address of the actor who triggered the event.
    • authRealm: [optional] Realm of the actor.
    • authUser: [optional] User ID of the admin who performed the action.
    • dateFrom: [optional] Start date in ISO 8601 format.
    • dateTo: [optional] End date in ISO 8601 format.
    • first: [optional] Pagination offset.
    • max: [optional] Maximum number of events to retrieve.
    • operationTypes: [optional] Filter by operation type (e.g., CREATE, UPDATE, DELETE).
    • resourcePath: [optional] Filter events by resource path.
    • resourceTypes: [optional] Filter events by resource type (e.g., USER, REALM_ROLE, CLIENT).

//  find 10 realm-id admin events with a type=CREATE|DELETE and dateFrom and dateTo. 
const config= await keycloakAdapter.kcAdminClient.realms.findAdminEvents({ 
    realm: 'realm-id',
    operationTypes: ['CREATE', 'DELETE'],
    dateFrom: '2025-08-01T00:00:00Z',
    dateTo: '2025-08-06T23:59:59Z',
    max: 10
});
function clearEvents(realmFilter)

Deletes all user events (not admin events) from the event store of a specific realm. Useful for resetting or cleaning up event logs related to user actions such as logins, logouts, failed login attempts, etc. This does not clear administrative events. To remove those, use realms.clearAdminEvents(). @parameters:

  • realmFilter: is a JSON object that accepts filter parameters
    • realm: [required] The name of the realm from which to clear user events.

//  clear realm-id events 
const config= await keycloakAdapter.kcAdminClient.realms.clearEvents({ 
    realm: 'realm-id',
});
function clearAdminEvents(realmFilter)

Deletes all admin events from the event store of a specific realm. Admin events include actions such as creating users, updating roles, changing client settings, etc., performed by administrators via the Admin Console or Admin REST API. @parameters:

  • realmFilter: is a JSON object that accepts filter parameters
    • realm: [required] The name of the realm from which to clear administrative events.

//  clear realm-id admin events 
const config= await keycloakAdapter.kcAdminClient.realms.clearAdminEvents({ 
    realm: 'realm-id',
});
function getUsersManagementPermissions(realmFilter)

Retrieves the status and configuration of user management permissions (also known as fine-grained permissions) in a specific realm. This allows you to check whether user management operations (like creating, updating, or deleting users) are protected by specific roles or policies.

@parameters:

  • realmFilter: is a JSON object that accepts filter parameters
    • realm: [required] The name of the realm for which you want to retrieve the user management permission settings.

Returns an object with information such as:

{
    enabled: boolean;
    resource: string;
    scopePermissions: {
          
    }
}

if enabled is false, user management operations are not restricted by fine-grained permissions. You can enable or configure these permissions using updateUsersManagementPermissions()


//  Get Permissions 
const permissions= await keycloakAdapter.kcAdminClient.realms.getUsersManagementPermissions({ 
    realm: 'realm-id',
});
console.log(permissions.enabled); // true or false
function updateUsersManagementPermissions(update-parameters)

Enables or disables fine-grained user management permissions in a specified realm. This controls whether operations on users (such as creating, editing, or deleting users) are protected using Keycloak's authorization services. @parameters:

  • update-parameters: is a JSON object that accepts this parameters
    • realm: [required] The name of the realm for which you want to update the user management permission settings.
    • enabled: [required] boolean value to enable or disable permission
      • true: Activates fine-grained permissions for user management.
      • false: Disables fine-grained permissions and falls back to standard admin roles.

Returns an object with information such as:

{
    enabled: boolean;
    resource: string;
    scopePermissions: {
          
    }
}
//  Update Permissions 
const permissions= await keycloakAdapter.kcAdminClient.realms.updateUsersManagementPermissions({ 
    realm: 'realm-id',
});

console.log(permissions.enabled); // true
function getKeys(filter)

Retrieves the realm keys metadata, including public keys, certificates, and active key information used for token signing, encryption, and other cryptographic operations in the specified realm. @parameters:

  • filter: is a JSON object that accepts this parameters
    • realm: [required] The name of the realm for which you want to retrieve key metadata.

Returns a list of keys and related information:

{
    keys: [
            {
                kid: string;          // Key ID
                type: string;         // Key type (e.g., RSA, AES)
                providerId: string;   // Key provider ID
                providerPriority:     //number;
                publicKey?: string;   // Base64-encoded public key (if applicable)
                certificate?: string; // X.509 certificate (if available)
                algorithm: string;    // Signing algorithm (e.g., RS256)
                status: string;       // Status (e.g., ACTIVE, PASSIVE)
                use: string;          // Intended use (e.g., sig for signature, enc for encryption)
            },
            ...
    ]
}
//  Get Keys 
const Keys= await keycloakAdapter.kcAdminClient.realms.getKeys({ 
    realm: 'realm-id',
});

console.log(Keys);
function getClientSessionStats(filter)

Retrieves statistics about active client sessions in the specified realm. This includes the number of active sessions per client. @parameters:

  • filter: is a JSON object that accepts this parameters
    • realm: [required] The name of the realm for which you want to retrieve client session statistics.

Returns an array of objects, each representing a client with active sessions

//  Get Client Session Stats 
const stats= await keycloakAdapter.kcAdminClient.realms.getClientSessionStats({ 
    realm: 'realm-id',
});

console.log(stats);
/*
[
  { clientId: 'frontend-app', active: 5 },
  { clientId: 'admin-cli', active: 1 },
  ...
]
*/
function pushRevocation(filter)

Immediately pushes a revocation policy to all clients in the specified realm. This forces clients to revalidate tokens, effectively revoking cached access tokens and enforcing updated policies. @parameters:

  • filter: is a JSON object that accepts this parameters
    • realm: [required] The name of the realm where the revocation should be pushed.
// push revocaiton to realm realm-id  
const pushR= await keycloakAdapter.kcAdminClient.realms.pushRevocation({ 
    realm: 'realm-id',
});

console.log(pushR);
function logoutAll(filter)

Logs out all active sessions for all users in the specified realm. This invalidates all user sessions, forcing every user to re-authenticate. @parameters:

  • filter: is a JSON object that accepts this parameters
    • realm: [required] The name of the realm from which to log out all users.
// force all users logout in realm realm-id  
const logout= await keycloakAdapter.kcAdminClient.realms.logoutAll({ 
    realm: 'realm-id',
});

console.log('logout results:',logout);
function testLDAPConnection(filter,options)

Tests the connection to an LDAP server using the provided configuration parameters. This is useful to verify that Keycloak can reach and authenticate with the LDAP server before fully integrating it into the realm configuration. @parameters:

  • filter: is a JSON object that accepts this filter parameters
    • realm: [required] Name of the realm where the LDAP provider is being tested.
  • options: is a JSON object that accepts this parameters
    • action: [required] Specifies the test type. Use "testConnection" to verify the connection, or "testAuthentication" to verify bind credentials.
    • connectionUrl: [required] URL of the LDAP server (e.g., ldap://ldap.example.com:389).
    • bindDn: [required] Distinguished Name (DN) used to bind to the LDAP server.
    • bindCredential: [required] Password or secret associated with the bind DN.
    • useTruststoreSpi: [optional] Whether to use the truststore ("ldapsOnly", "always", etc.).
    • connectionTimeout: [optional] Timeout value for the connection (in milliseconds).
    • authType: [optional] Type of authentication; usually "simple" or "none".
//should fail with invalid ldap settings
    try {
        await keycloakAdapter.kcAdminClient.realms.testLDAPConnection(
            { realm: "realm-name" },
            {
                action: "testConnection",
                authType: "simple",
                bindCredential: "1",
                bindDn: "1",
                connectionTimeout: "",
                connectionUrl: "1",
                startTls: "",
                useTruststoreSpi: "always",
            },
        );
        fail("exception should have been thrown");
    } catch (error) {
        console.log(error); // exception should have been thrown
    }
function ldapServerCapabilities(filter,options)

This function queries the LDAP server configured for a specific realm to retrieve and display its supported capabilities. It helps validate the connection and understand which LDAP features are available, such as supported controls, extensions, authentication mechanisms, and more. @parameters:

  • filter: is a JSON object that accepts this filter parameters
    • realm: [required] Name of the realm where the LDAP provider is being tested.
  • options: is a JSON object that accepts this parameters
    • action: [required] Specifies the test type. Use "testConnection" to verify the connection, or "testAuthentication" to verify bind credentials.
    • connectionUrl: [required] URL of the LDAP server (e.g., ldap://ldap.example.com:389).
    • bindDn: [required] Distinguished Name (DN) used to bind to the LDAP server.
    • bindCredential: [required] Password or secret associated with the bind DN.
    • useTruststoreSpi: [optional] Whether to use the truststore ("ldapsOnly", "always", etc.).
    • connectionTimeout: [optional] Timeout value for the connection (in milliseconds).
    • authType: [optional] Type of authentication; usually "simple" or "none".
// should fail with invalid ldap server capabilities
    try {
        await keycloakAdapter.kcAdminClient.realms.ldapServerCapabilities(
            { realm: "realm-name" },
            {
                action: "testConnection",
                authType: "simple",
                bindCredential: "1",
                bindDn: "1",
                connectionTimeout: "",
                connectionUrl: "1",
                startTls: "",
                useTruststoreSpi: "always",
            },
        );
        fail("exception should have been thrown");
    } catch (error) {
        console.log(error); // exception should have been thrown
    }
function testSMTPConnection(filter,config)

Tests the SMTP connection using the provided configuration. This allows you to verify that Keycloak can connect and send emails through the configured SMTP server before applying the settings to the realm. @parameters:

  • filter: is a JSON object that accepts this filter parameters
    • realm: [required] The name of the realm where the SMTP server will be tested.
  • config: An object containing the SMTP server configuration:
    • from: [required] The sender email address.
    • host: [required] The SMTP server host (e.g., smtp.example.com).
    • port: [required] The SMTP server port (usually 587, 465, or 25).
    • auth: [optional] Whether authentication is required ("true" or "false").
    • user [optional] The username for SMTP authentication.
    • password [optional] The password for SMTP authentication.
    • replyTo [optional] The reply-to email address.
    • starttls [optional] Enable STARTTLS ("true" or "false").
    • ssl [optional] Enable SSL ("true" or "false").
    • envelopeFrom [optional] Envelope sender address.
// should fail with invalid smtp settings
    try {
        await keycloakAdapter.kcAdminClient.realms.testSMTPConnection(
            { realm: "master" },
            {
                from: "[email protected]",
                host: "localhost",
                port: 3025,
            },
        );
        fail("exception should have been thrown");
    } catch (error) {
        console.log(error); // exception should have been thrown
    }
function getRealmLocalizationTexts(filter)

Retrieves all localization texts (custom messages and labels) defined for a specific realm and locale. Localization texts are used to override default Keycloak UI messages for login forms, error pages, and other user-facing content @parameters:

  • filter: is a JSON object that accepts this filter parameters
    • realm: [required] The name of the realm from which to fetch localization texts.
    • selectedLocale: [required] The locale code (e.g., 'en', 'it', 'fr', etc.) for which you want to retrieve the translations.
// Realm localization
const texts= await keycloakAdapter.kcAdminClient.realms.getRealmLocalizationTexts({ 
        realm: "realm-id",
        selectedLocale:'it'
});
console.log(texts); 
function addLocalization(filter,value)

Adds or updates a localization text (custom UI message or label) for a specific realm and locale in Keycloak. This allows you to override default messages in the login screens and other UI components with custom translations. @parameters:

  • filter: is a JSON object that accepts this filter parameters
    • realm: [required] The name of the realm where the localization should be applied.
    • selectedLocale: [required] The locale code (e.g., 'en', 'fr', 'it') for which the translation is being added.
    • key: [required] The message key or identifier to override (e.g., loginAccountTitle, errorInvalidUsername).
  • value: [required] The actual translated text to associate with the key for the given locale.
// should add localization
await keycloakAdapter.kcAdminClient.realms.addLocalization({ 
        realm: "realm-id",
        selectedLocale:'it',
        key:"theKey"
},"new Value String for key:theKey");
function getRealmSpecificLocales(filter)

Retrieves the list of locales (language codes) for which custom localization texts have been defined in a specific realm. This function is useful to determine which locales have at least one overridden message. @parameters:

  • filter: is a JSON object that accepts this filter parameters
    • realm: [required] The name of the realm for which to fetch the list of custom locales.
    • selectedLocale: [optional] The locale code (e.g., 'en', 'fr', 'it').

Return An array of locale codes (e.g., ["en", "it", "fr"]) representing the languages that have at least one customized localization entry in the given realm.

// should add localization
await keycloakAdapter.kcAdminClient.real