← Back to list

Integrating Keycloak with a Next.js Frontend and Securing API Calls via Kong API Gateway

In an era of increasing reliance on APIs and microservices, securing communication between clients and backend services has become a…

Eugene Tan · 2024-12-23 14:10 · 0 claps · 5.6 min read
#keycloak #keycloakjs #kong #openid-connect #nextjs
Open on Medium ↗
Wiki topics: 🌐 · Web Development

Integrating Keycloak with a Next.js Frontend and Securing API Calls via Kong API Gateway

In an era of increasing reliance on APIs and microservices, securing communication between clients and backend services has become a critical challenge. Microservice architectures, with their distributed nature, demand robust solutions for managing authentication and authorization across multiple services.

API Gateways like Kong play a pivotal role in this ecosystem by centralizing API traffic management, ensuring scalability, and enhancing security. However, to achieve secure and seamless access control, an identity provider is essential. This is where Identity Providers like Keycloak come in.

Keycloak, an open-source identity and access management solution, integrates seamlessly with Kong to handle user authentication, token issuance, and fine-grained authorization.

By delegating identity and access management to Keycloak and leveraging Kong’s OpenID Connect (OIDC) plugin for API protection, developers can ensure a consistent and secure authentication flow across services, adhering. This ensures consistency in a micro-services architecture to principles like single use responsibility, and help to loosely couple the identity services as its own service interface.

In this guide, we’ll dive deep into integrating Keycloak with a Next.js frontend application using the Keycloak JavaScript adapter. Additionally, we’ll demonstrate how to secure subsequent API calls using Kong API Gateway’s OpenID Connect (OIDC) plugin. This integration ensures robust user authentication and fine-grained API authorization by leveraging modern identity standards.

Key Concepts Behind the Integration

Before we delve into the setup, let’s break down the key components and their roles in the integration:

  1. Keycloak: An open-source identity and access management solution that supports OAuth 2.0, OpenID Connect (OIDC), and SAML. It acts as the identity provider (IdP) in this setup.
  2. Next.js Frontend: A React-based framework that serves as the user interface, integrated with Keycloak using the Keycloak JavaScript adapter.
  3. Kong API Gateway: A powerful API management tool that secures backend services by enforcing authentication and authorization using the OIDC plugin.

Workflow Overview

  1. User Authentication: The Next.js frontend uses the Keycloak JS adapter to handle user login and token management.
  2. Token Issuance: After successful authentication, Keycloak issues an ID token and access token.
  3. API Request Security: The access token is passed to Kong with each API request, where Kong validates the token’s authenticity and enforces access controls.
  4. Authorization: Kong uses group claims from the token to allow or deny access to specific resources.

Setting Up Keycloak

Step 1: Start Keycloak

Use Docker Compose to launch Keycloak:

docker-compose up

Access the Keycloak admin console at http://localhost:7080 and log in using the following credentials:

  • Username: admin
  • Password: admin

Step 2: Create a Realm

  1. Navigate to the admin console.
  2. Create a new realm called kong-frontend. A realm in Keycloak represents a namespace for managing users, credentials, roles, and clients.

Step 3: Configure a Client

  1. Under the kong-frontend realm, create a client named kong-frontend.
  2. Update the client settings:
  • Set Access Type to confidential.
  • Ensure Valid Redirect URIs include a trailing slash, e.g., [http://localhost:3001/*.](http://localhost:3001/*.)
  • Save the changes.

Step 4: Create a User

  1. Navigate to the Users section and create a new user.
  2. Set a username and save the user.
  3. Under the user’s Credentials tab, set a password and toggle the “Temporary” option to “Off”.

Setting Up the Next.js Frontend

Step 1: Install Dependencies

To use Keycloak with your Next.js app, install the necessary libraries:

npm install keycloak-js @react-keycloak/web

Step 2: Configure Keycloak in the App

  1. Create a keycloak.js file to configure Keycloak:
import Keycloak from 'keycloak-js';

const keycloakConfig = {
    url: 'http://localhost:7080/auth',
    realm: 'kong-frontend',
    clientId: 'kong-frontend',
};

const keycloak = new Keycloak(keycloakConfig);

export default keycloak;

Wrap your app with the Keycloak provider in _app.js:

import { ReactKeycloakProvider } from '@react-keycloak/web';
import keycloak from '../keycloak';

function MyApp({ Component, pageProps }) {
    return (
        <ReactKeycloakProvider authClient={keycloak}>
            <Component {...pageProps} />
        </ReactKeycloakProvider>
    );
}

export default MyApp;

Step 3: Start the Application

Run your Next.js app:

npm run dev

The app should be accessible at http://localhost:3001. Users can log in via Keycloak, and tokens are managed automatically by the adapter.

Setting Up Kong API Gateway

Step 1: Configure the OpenID Connect Plugin

  1. Create a Kong service and route for your API. Follow these steps here to do so.
  2. Add the OIDC plugin to the route:
  1. Update the OIDC plugin’s following settings to bypass localhost-related issues:

Execution: Authentication Flow

  1. Navigate to http://localhost:3001 and log in using the Keycloak credentials.
  2. Retrieve the access token from the Keycloak adapter (stored in the frontend state).
  3. Use the access token to authenticate API requests by including it in the Authorization header.

Example cURL command:

curl -X GET http://localhost:8000/api \
-H "Authorization: Bearer <ACCESS_TOKEN>"

Kong validates the token’s signature and introspects its claims to ensure it’s valid.

Adding Authorization with Keycloak Groups

Step 1: Configure Groups in Keycloak

  1. Navigate to Groups in your realm and create a group called developers.
  2. Add the user to this group.

Step 2: Map Groups to Tokens

  1. Navigate to Client Scopes > profile > Mappers > Create.
  2. Configure the mapper as follows:
  • Name: groups
  • Token Claim Name: groups
  • Include in token: Yes

Step 3: Update the OIDC Plugin in Kong

  1. Under the OIDC plugin’s Authorization section:
  • Add groups to the Authenticated Groups Claim field.

Step 4: Add the ACL Plugin

  1. Add an ACL plugin at the route level.
  2. Configure the plugin:
  • config.deny: developers
  • Enable Always Use Authenticated Groups
  • Save the configuration.

Execution: Authorization Flow

  1. Log in to the frontend app and retrieve a new access token.
  2. Verify the token on jwt.io to ensure the groups claim is present.
  3. Test the API with the token:

Example:

curl -X GET http://localhost:8000/api \
-H "Authorization: Bearer <ACCESS_TOKEN>"
  1. Modify the ACL plugin settings:
  • When developers is in config.deny, the response is 403 Unauthorized.
  • When developers is in config.allow, the response is 200 OK.

How It Works

User Authentication

  • The frontend app initializes Keycloak using the adapter, which handles the login process and manages tokens.
  • Keycloak issues tokens after successful authentication.

API Protection

  • The OIDC plugin in Kong verifies the token’s validity via introspection or JWKS.
  • Tokens are used to enforce authentication and authorization at the gateway level.

Group-Based Authorization

  • Group claims in tokens allow Kong to enforce fine-grained access control based on user roles.
  • ACL and OIDC plugins work together to allow or deny access to API routes.

Key Insights and Conclusion

This integration between Keycloak, Next.js, and Kong highlights several key benefits and insights that developers and organizations can leverage:

Seamless Authentication Workflow:

  • Keycloak’s JavaScript adapter simplifies user authentication by managing login states and token lifecycles on the frontend. This minimizes development complexity while ensuring secure access to the application.

Centralized Identity Management:

  • Using Keycloak as an identity provider enables organizations to centralize user management, making it easier to implement consistent policies for login, password management, and role assignments across multiple applications.

API Security with Kong:

  • Kong’s OIDC plugin provides robust mechanisms to secure APIs by validating tokens issued by Keycloak. Features like introspection and JWKS endpoint support make it highly adaptable to different environments and configurations.

Fine-Grained Authorization:

  • The combination of Keycloak’s group claims and Kong’s ACL plugin allows precise control over who can access specific API routes. This is particularly valuable for implementing role-based access control (RBAC) in modern applications.

Scalability and Statelessness:

  • Leveraging JWT tokens ensures a stateless authentication system, which is essential for scalability in distributed systems. Kong’s lightweight validation mechanisms enhance performance by offloading complex authorization logic from backend services.

Future-Proof Security:

  • By adopting open standards like OAuth 2.0 and OpenID Connect, this setup ensures compatibility with other identity providers and API gateways, making it a sustainable choice for evolving application ecosystems.

Conclusion

This guide demonstrates the integration between Keycloak and Kong to build secure, scalable, and user-friendly applications. By using Keycloak for identity management and Kong for API protection, such allows applications to scale via a platform approach.

This decoupling of any operational logic around authentication and traffic management from the application code itself, increasing the time to market for new applications and features.


메타데이터
post_id
dabd9d691f5c
slug
integrating-keycloak-with-a-next-js-frontend-and-securing-api-calls-via-kong-api-gateway-dabd9d691f5c
url
https://medium.com/@eugenetan_91090/integrating-keycloak-with-a-next-js-frontend-and-securing-api-calls-via-kong-api-gateway-dabd9d691f5c
canonical_url
https://medium.com/@eugenetan_91090/integrating-keycloak-with-a-next-js-frontend-and-securing-api-calls-via-kong-api-gateway-dabd9d691f5c
author_url
https://medium.com/@eugenetan_91090
status
ok
fetched_at
2026-06-20 20:29:01