Implementation of Keycloak for Modern Applications

Implementation of Keycloak for Modern Applications

In the digital era, robust identity and access management systems are crucial for secure applications. Keycloak stands out as an open-source solution that simplifies user authentication and authorization with enterprise-grade features.

This blog dives deep into the essentials of Keycloak, guiding you through its configuration and usage with practical examples and code snippets. It also covers how tokens are used in Keycloak for secure communication and how frontend integration works.


Table of Contents

  1. Introduction to Keycloak
  2. Initial Setup and Configuration
  3. Setting Up Keycloak and Key Features
  4. Hands-On Example: Keycloak Integration
  5. Tokenization: Frontend and Backend Integration
  6. Conclusion

Introduction to Keycloak

Keycloak is an open-source identity and access management tool that enables:

  • Single Sign-On (SSO): Login once, access multiple applications.
  • Identity Management: Centralized control over users, roles, and permissions.
  • Security: Advanced features like multi-factor authentication (MFA), social login, and token-based validation using OpenID Connect or OAuth2 protocols.

With Keycloak, developers can reduce implementation complexity while ensuring high-security standards.


Initial Setup and Configuration

Prerequisites

  1. A running Keycloak instance.
  2. Admin credentials for Keycloak.
  3. Basic understanding of authentication and authorization.

Configuring Keycloak for Your Application

To integrate Keycloak into your application, update the configuration files like appsettings.json, appsettings.Development.json, and config.js with the following details:

"SSO": {
    "AuthType": "SSO",
    "BaseUrl": "http://your-keycloak-url:8080",
    "Realm": "your-realm",
    "ClientId": "your-client-id",
    "Issuer": "keycloakIssuer",
    "Audience": "keycloakIssuer",
    "PublicKey": "<Your_Public_Key_Here>"
}
  • AuthType: Specifies the authentication type (e.g., SSO).
  • BaseUrl: URL of the Keycloak server.
  • Realm: The realm your application belongs to.
  • ClientId: Identifier for your application.
  • Issuer & Audience: Validate token authenticity.

Token Refresh Configuration

"KC_TOKENREFRESHINTERVAL": 300000,
"KC_TOKENREFRESH_BEFOREEXPIRY": 60
  • KC_TOKENREFRESHINTERVAL: Time interval (in ms) for refreshing the token.
  • KC_TOKENREFRESH_BEFOREEXPIRY: Time (in seconds) before expiry to request a new token.

Setting Up Keycloak and Key Features

Accessing Keycloak Admin Console

  1. Navigate to your Keycloak instance: http://your-keycloak-url:8080/admin.
  2. Log in using admin credentials.

Adding a User

  1. Select the appropriate realm.
  2. Go to Users > Add User.
  3. Enter details (Username, Email, First Name, Last Name) and click Save.
  4. Under the Credentials tab, set a temporary password.

Creating a Client

  1. Navigate to Clients and click Create.
  2. Enter a unique Client ID (e.g., my-web-app) and select Client Protocol as openid-connect.
  3. Configure Redirect URIs for login redirection.
  4. Save and adjust settings like Access Type (public or confidential) and authorization.

Hands-On Example: Keycloak Integration

Frontend Configuration (Angular Example)

Add Keycloak initialization in main.ts:

import Keycloak from 'keycloak-js';

const keycloak = new Keycloak({
    url: 'http://your-keycloak-url:8080',
    realm: 'your-realm',
    clientId: 'your-client-id'
});

keycloak.init({ onLoad: 'login-required' }).then(authenticated => {
    console.log(authenticated ? 'Authenticated' : 'Not authenticated');
}).catch(console.error);

Backend Validation (ASP.NET Example)

Use middleware to validate tokens:

public void ConfigureServices(IServiceCollection services)
{
    services.AddAuthentication(options =>
    {
        options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
        options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
    })
    .AddJwtBearer(options =>
    {
        options.Authority = "http://your-keycloak-url:8080/realms/your-realm";
        options.Audience = "your-client-id";
        options.TokenValidationParameters = new TokenValidationParameters
        {
            ValidateIssuerSigningKey = true,
            ValidateIssuer = true,
            ValidateAudience = true
        };
    });
}

Tokenization: Frontend and Backend Integration

Frontend Tokenization

To ensure secure communication between your frontend application and Keycloak, you need to obtain and pass an access token. Once the user is authenticated with Keycloak, you can retrieve the token and include it in API requests.

Example:

const token = keycloak.token;
  • Store the token securely (e.g., in memory) and use it for API calls.
  • Example of passing the token in an HTTP request:
const headers = new HttpHeaders().set('Authorization', 'Bearer ' + token);
this.http.get('https://api.yourserver.com/data', { headers }).subscribe(response => {
    console.log(response);
});

Backend Token Validation

In the backend, the token passed from the frontend needs to be validated to ensure the request's authenticity and integrity.

For example, in an ASP.NET backend, you can configure token validation middleware as shown below:

public void ConfigureServices(IServiceCollection services)
{
    services.AddAuthentication(options =>
    {
        options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
        options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
    })
    .AddJwtBearer(options =>
    {
        options.Authority = "http://your-keycloak-url:8080/realms/your-realm";
        options.Audience = "your-client-id";
        options.TokenValidationParameters = new TokenValidationParameters
        {
            ValidateIssuerSigningKey = true,
            ValidateIssuer = true,
            ValidateAudience = true
        };
    });
}

The middleware will automatically validate the token's issuer, audience, and signature, ensuring that only valid requests are processed.


Conclusion

Keycloak stands out as a reliable, robust, and feature-rich identity and access management solution for modern applications. Its capabilities, including Single Sign-On (SSO), Role-Based Access Control (RBAC), Multi-Factor Authentication (MFA), and seamless integration with popular protocols like OAuth2.0 and OpenID Connect, make it an essential tool for securing applications across diverse platforms.

By simplifying the complexities of authentication and authorization, Keycloak empowers organizations to achieve high-security standards while enhancing user experience. Whether you are managing enterprise-scale applications, APIs, or microservices, Keycloak’s scalability and customization options ensure it aligns perfectly with your business needs.

Implementing Keycloak effectively can transform how you manage identity and access, strengthening your security posture and fostering trust among users. It’s a solution designed to scale with your ambitions, ensuring a secure and future-ready application environment.

💡 If you’re looking to leverage Keycloak for your organization or need guidance in your implementation journey, feel free to connect!

👉 Connect with me on LinkedIn: Deep Modak