Keycloak: SSO Solution

Introduction to Keycloak

It’s becoming increasingly important to secure applications. Not only that, but illegal access to protected data can result in millions of dollars in financial penalties. All applications require trustworthy methods to handle user identities and access rights. Keycloak is an open-source identity and access management (IAM) technology that manages application and service user authentication, authorization, and single sign-on (SSO). Keycloak operates on industry-standard protocols, including OAuth 2.0, OpenID Connect, and SAML 2.0, making the interface with various applications and platforms simple. Keycloak is especially suitable for enterprises using microservices architectures or with many applications and services.

Among the many IAM solutions available, Keycloak stands out as a durable and versatile platform for authentication and authorization. This article will examine how to get started with Keycloak, its advanced features, and customization. You’ll also learn more about Keycloak’s Best Practices and integration, User Management, Authentication Mechanisms, and securing Applications with Keycloak. 

  • What is Keycloak?

Keycloak is a Java-based, open-source Identity and Access Management tool created by Red Hat, an American software company noted for contributing to open-source projects. It is an open-source tool licensed under Apache License 2.0. with Keycloak, you can protect services and add authentication to applications.

  • Why is Identity and Access Management (IAM) important?

Identity and Access Management (IAM) is essential for various reasons, including increased business security and efficiency. Its importance grows in today’s digital ecosystem as cyber threats and complicated I.T. settings become more prevalent. It guarantees that the right people in an organization have proper access to resources. Its tools often support the implementation of SSO, identity federation, and strong authentication.

  • Keycloak’s role in IAM

An effective IAM platform must do more than meet current security requirements; it must also help firms plan for the future. Keycloak IAM is well-equipped to fulfill this task. 

Keycloak plays a vital role in the IAM ecosystem by providing numerous critical functionalities. It enables enterprises to personalize the IAM solution to their requirements by delivering customized extensions and support for their SPI providers. 

Keycloak IAM is a strategic tool that may help firms prepare for emerging cybersecurity threats. Its support for standard protocols, ability to interact with other systems, scalability, customizability, user-centric features, compliance with data protection regulations, and 24-hour support make it a future-proof IAM solution.

Getting Started with Keycloak

Getting started with Keycloak on bare metal is a 10-step procedure. However, Java must be installed before Keycloak may run on your system. This is because Keycloak is a Java application that requires the Java Runtime Environment (JRE) to function. Before you begin, ensure OpenJDK 17 is installed. Keycloak requires OpenJDK 17 or later. OpenJDK is a free, open-source Java Platform, Standard Edition implementation.

  • Installation and setup

Before installing OpenJDK, ensure you have a server running a compatible Linux distribution (e.g., Ubuntu) with Java 11 installed. Updating Ubuntu to ensure all system packages are current with the “apt update” command is essential. This helps to prevent any potential conflicts during the installation process. To update your Ubuntu system, run the following command in your terminal.


Depending on your version of Ubuntu, you can install OpenJDK 17 JRE (Java Runtime Environment) and JDK (Java Development Kit) using the following command. This is only applicable if these packages are available in your distribution:

To check if the installation was successful, run the following command in your terminal:

You can choose any directory you have write permissions to download the Keycloak package and unzip. The package will be installed in the directory where you run the wget command. 

Once you’ve downloaded and verified the package, you can use the cd command to change the directory where you downloaded the archive. This will create a directory named keycloak-15.0.2 within the chosen directory.

To manually start Keycloak, navigate to the unzipped directory and run:

  • Configuration options

Before starting Keycloak, it’s essential to choose appropriate configuration options. These options customize Key Cloak’s behaviour and security based on your needs. This includes

  1. Authentication: Admin User (e.g., username/password, social logins). Keycloak has no default admin user. You need to create an admin user before you can start Keycloak.
    1. Open http://localhost:8080/
    2. Fill in the form with your preferred username and password.
  1. Authorization: Set up roles and permissions for user access control. 
  1. You will go to the Keycloak Admin Console
  2. Log in with the username and password you created earlier.
  1.     Realms and Clients: Create isolated authentication spaces and applications relying on 


  • Setting up realms and clients

Setting up realms and clients on Keycloak is crucial in utilizing its powerful identity and access management features. It is a space where you manage users, roles, and groups. It’s a container for user authentication and authorization settings.

A realm can represent a logical space for a set of users, for example, all company employees or users of a specific application. Setting up realms and clients on Keycloak can offer several personal benefits, depending on your particular goals and context. Users within a realm can enjoy Single Sign-On (SSO) abilities to seamlessly access multiple applications using the same login credentials, eliminating the need to repeatedly sign in to each platform. 

    Create the first realm by following these steps. 

  1. Click the Keycloak Admin Console.
  2. Click the “Master” menu dropdown and select “Add realm”.


User Management

  • Creating and managing users

   Create a user by following these steps:

  1. Click the Keycloak Admin Console.
  2. Enter a name for your realm (e.g., “my-app-realm”) and click “Create.”
  3. This creates a logical container for your users, roles, and clients. Avoid using the “master” realm for production applications.
  4. Navigate to “Users” in the realm menu.
  5. Click on “Add user”.
  6. Provide user details like username, email, first name, and last name.
  7. Click Create.


 Managing Users:

  1. Click on the user to access their details and perform actions:
  2. Reset or require the user to set a new password.
  3. Manage user login access.
  4. Modify user information.
  5. Grant user-specific permissions within the realm.


To verify if the user if the user is configured correctly, 

  1. Click the Keycloak Admin Console.
  2. Log in with the username and password you created earlier.

  • User federation options

In Keycloak, the term “user federation” refers to the capability of integrating with external identity stores. Keycloak offers various user federation options to integrate with existing user directories and authenticate users seamlessly. Standard user federation options include:

  1. Social Login Providers like Google, Facebook, and GitHub. 
  2. LDAP Federation: Keycloak connects to external LDAP directories like Active Directory or OpenLDAP and Sync user information from the directory to Keycloak
  3. SAML 2.0 Federation: It suits complex SSO (Single Sign-On) setups with multiple providers.
  •  Password policies and security

Strong password policies and robust security measures are essential in Keycloak.

For the Password Policies

  1. Navigate to “Authentication” > “Password Policy” in your realm.

     2. Activate desired policies from the available options:

  • Enforce a minimum character count (recommended: 12+).
  • Mandate a mix of character types for stronger passwords.
  • Prevent using previously used passwords.
  • Configure password expiry intervals (consider regular updates)
  • Implement lockout mechanisms to deter brute-force attacks.
  1.   Adjust individual policy parameters as needed.


For the Security Measures: 

  1. Enable the Two-Factor Authentication (2FA) step (e.g., TOTP, WebAuthn) for heightened login security.

     2. Verify user ownership and prevent unauthorized registrations by configuring email verification

      3. and secure communication channels with HTTPS and TLS/SSL certificates for solid encryption.


Authentication Mechanisms

  • Overview of authentication methods supported by Keycloak

Authentication is a series of successive processes or executions combined to validate the user’s identity. You can customize this by replicating existing built-in flows, adjusting flow priorities, or eliminating a few. Keycloak offers diverse authentication mechanisms through SPIs (Service Provide Interfaces) to cater to security needs and user preferences.

Keycloak offers a simple authentication technique for services and apps. It uses industry-standard protocols and supports SAML 2.0, OpenID Connect (OAuth 2.0 + Authentication Layer), and OAuth 2.0. It utilizes its user database but may also be connected with existing user directories, such as LDAP servers and Active Directory. This includes the Traditional password-base (Username/Password) authentication systems. Users authenticate with their existing social media accounts like Facebook, Google, and GitHub. 

  • Configuring social logins (Google, Facebook, etc.)

To configure social logins in Keycloak:

  1. Navigate to “Clients” in the realm menu.

    2. Select your client or create a new one.

     3. Go to the “Authentication” tab.

     4. Enable the desired social login providers (e.g., Facebook).

      5. Provide necessary configuration details for each provider (e.g., Client ID).

       6. Save the client configuration.

  •  Implementing Multi-Factor Authentication (MFA)

Multi-factor authentication (MFA) emerges as a formidable solution, adding more protection beyond passwords. Nowadays, securing online identities and data is of critical importance. Traditional password-based authentication systems are growing more vulnerable to cyberspace’s constantly developing dangers. Multi-factor authentication (MFA) considerably minimizes the risk of illegal access, even when one of the factors is compromised. Implementing Multi-Factor Authentication (MFA) enhances security by adding an extra layer of verification beyond passwords.

Implementing Multi-Factor Authentication with Keycloak involves strategic configuration steps to ensure a seamless and secure process. The following steps guide administrators through the setup.

  1. Log in with administrator credentials to access the Administration Console, which allows for adjusting authentication settings.
  2. In the Administration Console, go to the Authentication settings area to configure various authentication options.
  3. Enable Multi-Factor Authentication for the chosen realm or client, selecting from TOTP, HOTP, SMS, or biometric authentication options based on organizational security needs.
  4. Configuring MFA Policies: Set up Multi-Factor Authentication policies depending on security needs, considering situations, user roles, and temporal regulations. This stage ensures that MFA is used contextually and for specific organizational needs. 
  5. Guide users through a simple Multi-Factor Authentication signup procedure. An intuitive and user-friendly onboarding experience is critical for fostering widespread adoption by end users. 
  6. Test and Verification: Extensive testing is required before establishing Multi-Factor Authentication in a production environment.

Authorization and Permissions

  • Defining roles and permissions

Roles define a kind or category of user. Admin, user, manager, and employee are all typical roles that may exist in an organization. Users can be assigned multiple roles. Applications frequently grant access and permissions to specific roles rather than individual users because dealing with people can be too fine-grained and challenging to manage. Permissions are granular access controls within roles (e.g., “create posts” and “edit comments”) and configure permissions within client roles or realm roles (accessible under the “Roles” tab). Keycloak allows you to establish and maintain granular access restrictions within your realm by leveraging roles and permissions.

Steps for defining roles and permissions:

a. Create Roles.

              1. Visit the “Clients” area. 

              2. Select your client. 
3. Go to the “Roles” tab.

  1. Click “Add role” and enter a name and description. 

  1. Optionally, use pre-defined permission settings like “view realm.” 


     b.  Assign Permission to Roles: 

  1. Select a role under the “Roles” tab. 

  1. Navigate to the “Permissions” tab. 

  1. Select “Add Permissions” or “Add Scopes” based on the client type. 
  2. Allow particular resources and activities for the job, such as “read users” and “update articles.” 
  • Role-based access control (RBAC)

Role-based access control (RBAC) restricts network access depending on the user’s organizational role and clearance level. Not all workers have full access to the company’s information. RBAC controls information access, ensuring workers can only access the authorized information. 

Role-based access control (RBAC) allows organizations to add and alter roles across operating systems, platforms, and apps without paperwork. Roles may be issued or removed, which is particularly useful for keeping track of external third-party users. Responsibility, authority, and job competency are all crucial considerations in determining who has access to what resources. 

RBAC is important for enterprises with many workers and those using third-party suppliers, contractors, and external consultants.

  • Fine-grained authorization policies

Keycloak empowers you to implement fine-grained authorization policies, enabling precise control over user access to resources within your realm. This goes beyond essential role-based access control (RBAC) (RBAC) by considering additional factors like user attributes, context, and time-based restrictions.

Keycloak offers fine-grained authorization policies and may combine several access control techniques, such as:

  1. Attribute-Based Access Control (ABAC) grants access based on user attributes, such as department, location, and role in an external system.
  2. Policy Enforcement Points (PEPs): Expand authorization logic beyond Keycloak to include bespoke apps or other systems.
  3. Use Time-based Access Control (TBAC) to restrict access based on specific times or schedules.
  4. Context-based Access Control (CBAC) uses environmental factors such as device kind, location, or I.P. address to make permission choices.
  5. Rule-based Access Control: Use JavaScript to define complicated authorization rules.

Implementing Fine-grained Policies:

  • Access the Keycloak Policies section from “Clients” -> “Resource Server.”
  • Develop policies utilizing the approaches above, such as ABAC, PEPs, and TBAC. 
  • Specify access conditions and rules. 
  • Consider user traits, context, and other variables while developing policies. 

Securing Applications with Keycloak

Securing applications with Keycloak involves integrating an external Identity and Access Management (IAM) system to manage user authentication, authorization, and access control.

  • Integrating Keycloak with web applications

Integrating Keycloak with your web application seamlessly protects your resources and simplifies access management.

Steps on how to integrate Keycloak with web applications

  1. Choose a client adapter library based on your web framework (e.g., Keycloak JavaScript adapter for J.S. frameworks, Spring Security for Java applications).
  2. Add the Keycloak JavaScript adapter to your frontend application by including the Keycloak JavaScript library in your HTML files.
  3. Configure the adapter in your application with the Client ID, Client Secret (if confidential), and Keycloak server URL.
  4. Initialize the Keycloak adapter in your application to handle user authentication, token acquisition, and session management.
  • Securing APIs with Keycloak

Securing APIs with Keycloak involves implementing an OAuth 2.0 authorization flow to protect your API endpoints and grant access only to authorized users. Other servers include OpenID Connect and SAML-compliant servers. Keycloak can secure any APIs if the technology stack supports these protocols. 

Steps on how to secure APIs with Keycloak.

  1. Set up users, roles, and permissions within the Keycloak domain to govern access to your API.
  2. Input pertinent information such as the Client ID, Client Secret (for confidential clients), Redirect URIs (for web-based clients), and Access Type (public or personal) when registering the API as a client in Keycloak.
  3. Specify in the configuration or annotations of your API endpoints that authorization requires authentic access tokens from Keycloak.
  4. Implement logic to authenticate the access credentials obtained through API requests by employing the introspection endpoint or public keys of Keycloak. 
  5.  Determine the suitable flow according to the nature of the API and the necessary security measures (e.g., Authorization Code Flow for web applications).
  • Session management and SSO (Single Sign-On)

Keycloak is vital in managing user sessions and enabling SSO for web applications and services. Keycloak provides centralized session management, eradicating individual applications’ need to oversee sessions independently. 

This facilitates administrative tasks and ensures users encounter a uniform interface across all applications. Keycloak provides administrators with APIs to manage, terminate, and observe user sessions. This permits features such as forced logout and surveillance of suspicious activity. Multiple SSO protocols, such as OpenID Connect, SAML 2.0, and Kerberos, are supported by Keycloak. 

This facilitates the incorporation of various application categories and identity providers. Users are granted access to any Keycloak application with a single authentication attempt. This feature enhances the user experience by eliminating the necessity for repeated credential entry. The session information is disseminated to all authorized applications upon successful authentication, enabling uninterrupted access without additional verification.

Advanced Features and Customization

In addition to its fundamental functionalities, such as single sign-on (SSO) and session management, Keycloak provides many advanced features and customization alternatives that cover a wide array of security and access control requirements. Advanced Features include Multi-Factor Authentication (MFA), Account Management, Permissions and Scopes, and Token Exchange.

  • Customizing login themes

The customization login theme includes the following:

  1. Customize email templates for notifications, password resets, and user communication to reflect your organization’s tone and branding. 
  2. Theme SPI to create custom themes and control user interface components and behaviours
  3. Customize Keycloak’s web interfaces (login, registration, and account management) to align with your application’s branding or requirements. 
  4. Extend Keycloak’s capabilities using community-developed extensions that add features or integrate with specific technologies. 
  5. Configuration Options: Customize Keycloak’s behaviour using server configuration files or environment variables.
  • Extending Keycloak functionality with plugins 

Keycloak includes a sophisticated mechanism for extending its capabilities via plugins. These plugins enable you to add unique features, interface with external systems, and customize Keycloak to meet your individual needs. Implementation of Keycloak with plugins includes: 

  1. SPI (Service Provider Interface): These plugins boost Keycloak’s fundamental functionality by implementing Keycloak-defined interfaces. Examples include bespoke authentication routines, user federation providers, and event listeners.
  2. Quarkus Extensions: These plugins employ Keycloak’s Quarkus framework to provide custom functionality such as custom endpoints, database connectors, and other services.
  3. Community-Developed Extensions: There is a robust ecosystem of community-developed extensions that provide a variety of capabilities and integrations that Keycloak does not officially support. 
  • Advanced user federation strategies

Beyond essential user federation with standard protocols like SAML and LDAP, Keycloak offers several advanced user federation strategies to enhance security, flexibility, and user experience; advanced user federation strategies include:

  1. Just-in-Time (JIT) Provisioning: This eliminates the need to pre-provision users, simplifies user administration, and lowers administrative expenses, particularly for large businesses. Implement appropriate access control to ensure that only authorized users are provisioned. 
  2. Attribute-Based Access Control (ABAC): It enables more flexible and context-aware permission decisions. It specifies unambiguous attribute mapping rules between the IdP and Keycloak. Maintain consistency and accuracy in attribute retrieval for access control. 
  3. Multi-Factor Authentication (MFA): It provides additional choices beyond Keycloak’s built-in capabilities. It offers users more options and more convenient approaches. It ensures interoperability between Keycloak and the selected external MFA. Provider.

Keycloak Best Practices

Keycloak provides a robust solution for managing user authentication and authorization, but applying it successfully necessitates adhering to best practices to ensure maximum security and user experience.

  • Security best practices

The Key aspects of keycloak security best practices include Realm Configuration, Client Configuration, Access Control, and Authorization. 

  1. For Realm Configuration:
  • Implement advanced password rules for users and service accounts. 
  • Provide Two-Factor Authentication (2FA) for influential users and roles.
  • Collect just essential user data and apply suitable access constraints. 
  • Respond quickly to security issues.
  1.     For Client Configuration:
  • Use HTTPS for communication between clients, Keycloak, and protected resources. 
  • Prevent phishing attempts by specifying genuine URLs for redirection after login.
  •  Ensure client certificates are validated for safe connection. 
  • Provide just essential scopes to clients to prevent excessive access.
  1.      For Access Control and Authorization:
  • Grant users and roles just the necessary access for their responsibilities. 
  • Use attribute-based access control (ABAC) or other F.G.A.C. techniques for more precise control. 
  • Provide robust network segmentation and access rules to safeguard Keycloak and resources. 
  • Stay current on security risks and best practices for Keycloak and OAuth 2.0.


  • Performance optimization tips

Keycloak provides robust security and access control capabilities; optimizing its performance is critical for a smooth user experience and adequate resource consumption. 

  1. Use Keycloak’s built-in caching for user sessions, permissions, and frequently requested data.
  2. Ensure tokens, sessions, and cached data have proper expiry durations for optimal security and speed. 
  3. Execute massive user activities (e.g., password resets) outside peak hours to reduce the effect on user requests. 
  4. Regularly examine Keycloak logs and analytics to detect bottlenecks and enhance performance.
  5. Use efficient login flows, such as the Client Credentials Flow, for machine-to-machine communications. 


  • Disaster recovery and backups

A strong disaster recovery (DR) and a backup plan are critical for guaranteeing the availability and integrity of your Keycloak data, particularly in the event of unanticipated occurrences such as hardware failures, cyberattacks, or natural disasters.

  1. Regularly backup your Keycloak server, including database, configuration files, and user data. This frequency should be determined depending on your risk tolerance and data sensitivity. 
  2. Ensure backups are reliable and usable after completion. Test restores regularly to ensure your disaster recovery strategy works appropriately.
  3. Clarify your disaster recovery strategy, including roles, duties, processes, and communication protocols. Train your team on the plan consistently.


Keycloak Integrations

  • Integrating Keycloak with popular frameworks and platforms (Spring Boot, Angular, React, etc.)

Keycloak interacts smoothly with many frameworks and platforms, facilitating user authentication, authorization, and access control inside your apps. Keycloak can be integrated with some frameworks and platforms (Spring Boot, Angular, and React).

Spring Boot provides startup dependencies such as keycloak-spring-boot-starter and keycloak-spring-security-adapter for easy integration: Configure Keycloak client details, authorization server information, and secure URLs in your Spring Security settings. 

For angular, Libraries for communicating with Keycloak and managing tokens include @angular/common/HTTP and angular-auth. They implement login and logout routines, access user characteristics, and secure routes depending on roles or permissions.

Keycloak integrates with React utilizing OpenID Connect-based authentication and direct integration. The react-openid-connect library is a well-known solution for OpenID Connect-based authentication and SSO. If you want a direct connection with the Keycloak server or prefer a different library, react-keycloak provides options.


  • Using Keycloak with Docker and Kubernetes

Keycloak can be used with Docker and Kubernetes clusters by building deployments and services. This enables you to deploy and manage it in containerized environments.

Steps on how to utilize Keycloak with Docker 

  1. Use’s official Keycloak Docker image ( 
  2. Customize the image by mounting configuration files or setting environment variables. 
  3. Begin the container with port mappings for Keycloak’s ports (default: 8080).

Steps on how to utilize Keycloak with Kubernetes 

  1.  Create a deployment manifest file to specify Keycloak pods, replica count, and resource requests/limits.
  2. Add Keycloak support to a Kubernetes service type, such as ClusterIP or headless.
  3. Use secrets or ConfigMaps to store Keycloak configuration securely.


Real-world Use Cases and Examples

Keycloak, an open-source identity and access management (IAM) solution, is used in various real-life scenarios and industries.

  • Case studies showcasing Keycloak implementations

There are several resources showcasing successful Keycloak implementations across various industries:

  1. HeartAI:
  • Industry: Healthcare
  • Use Case: HeartAI utilizes Keycloak for secure user authentication and access control for their AI-powered healthcare platform. They leverage features like SSO, multi-factor authentication, and role-based access control to ensure patient data security and compliance with HIPAA regulations.
  1. Red Hat:
  • Industry: Technology
  • Use Case: Red Hat utilizes Keycloak for internal access management across various products and services. This allows them to centralize user authentication, enforce access policies, and simplify user management for a large, distributed workforce.
  1. F-Secure:
  • Industry: Cybersecurity
  • Use Case: F-Secure, a leading cybersecurity company, leverages Keycloak for user authentication and authorization for their cloud-based security solutions. This enables them to provide secure access to their services while adhering to strict security standards.
  • Common scenarios and solutions

Here are some common scenarios and their solutions using Keycloak:

  1. Single Sign-On (SSO):
  • Problem: Users must log in to each application separately, creating a cumbersome experience.
  • Solution: Keycloak acts as a central authentication server. Users log in once to Keycloak and access all authorized applications without re-entering credentials.

      2. Social Login Integration:

  • Problem: Users prefer logging in with existing social media accounts (e.g., Google, Facebook) for convenience.
  • Solution: Keycloak integrates with social login providers, allowing users to authenticate using their social media credentials.

      3. Multi-Factor Authentication (MFA):

  • Problem: Password-based authentication alone is vulnerable.
  • Solution: Keycloak supports various MFA methods like SMS codes, hardware tokens, or biometrics, adding an extra layer of security.
  1. Role-Based Access Control (RBAC):
  • Problem: Different users need varying levels of access to application resources.
  • Solution: Keycloak allows defining roles and assigning them to users or groups. Applications can then enforce access based on set roles.


  • Summary of Keycloak’s benefits and capabilities

Keycloak empowers secure and streamlined access management. It simplifies user experience with SSO, self-service features, and social login integration. Security is bolstered through solid passwords, MFA, and RBAC. Its open-source nature, cloud-friendly design, and plugin architecture ensure flexibility and scalability. Integration capabilities and API security further solidify Keycloak’s value proposition. Keycloak offers a comprehensive solution for efficient and secure identity and access management.

  • Future trends in IAM and Keycloak’s role in it

The future of identity and access management (IAM) promises exciting advancements driven by evolving user needs, security concerns, and technological innovations. One key trend is the continued rise of cloud-based applications and APIs. This necessitates robust access control mechanisms that extend beyond traditional perimeter security. Keycloak’s cloud-friendly nature and API security features suit this evolving environment well.

Adaptive authentication is another emerging trend, where access decisions are based on real-time factors like user behavior, location, and device. Another significant trend is the growing adoption of passwordless authentication methods like biometrics and hardware tokens. Keycloak’s support for various MFA methods positions it to cater to this shift towards more secure and convenient authentication mechanisms.

Furthermore, decentralized identity (DID) solutions are gaining traction, offering users greater control over their data. Keycloak can potentially integrate with DID providers, enabling organizations to leverage the benefits of decentralized identity while maintaining robust access management within their applications.

In conclusion, By embracing emerging trends like cloud security, adaptive authentication, passwordless methods, and decentralized identity, Keycloak can continue to empower organizations with secure and efficient identity and access management solutions.


Keycloak: SSO Solution

Introduction to Keycloak It’s becoming increasingly important to secure applications. Not only that, but illegal access to protected data can result in millions of dollars

Read More »

Golang vs Rust

If you work in the tech industry or follow a lot of technical blogs, you’re bound to have come across Golang and Rust. Both of

Read More »

Thank You!

Our manager will contact you within 1 business day