• Explore the unified API Platform
        • BUILD APIs
        • Kong Insomnia
        • API Design
        • API Mocking
        • API Testing & Debugging
        • MCP Client
        • RUN APIs
        • API Gateway
        • Context Mesh
        • AI Gateway
        • Event Gateway
        • Kubernetes Operator
        • Service Mesh
        • Ingress Controller
        • Runtime Management
        • DISCOVER APIs
        • Developer Portal
        • Service Catalog
        • MCP Registry
        • GOVERN APIs
        • Metering & Billing
        • APIOps & Automation
        • API Observability
        • Why Kong?
      • CLOUD
      • Cloud API Gateways
      • Need a self-hosted or hybrid option?
      • COMPARE
      • Considering AI Gateway alternatives?
      • Kong vs. Postman
      • Kong vs. MuleSoft
      • Kong vs. Apigee
      • Kong vs. IBM
      • GET STARTED
      • Sign Up for Kong Konnect
      • Documentation
  • Agents
      • FOR PLATFORM TEAMS
      • Developer Platform
      • Kubernetes & Microservices
      • Observability
      • Service Mesh Connectivity
      • Kafka Event Streaming
      • FOR EXECUTIVES
      • AI Connectivity
      • Open Banking
      • Legacy Migration
      • Platform Cost Reduction
      • Kafka Cost Optimization
      • API Monetization
      • AI Monetization
      • AI FinOps
      • FOR AI TEAMS
      • AI Cost Control
      • AI Governance
      • AI Integration
      • AI Security
      • Agentic Infrastructure
      • MCP Production
      • MCP Traffic Gateway
      • FOR DEVELOPERS
      • Mobile App API Development
      • GenAI App Development
      • API Gateway for Istio
      • Decentralized Load Balancing
      • BY INDUSTRY
      • Financial Services
      • Healthcare
      • Higher Education
      • Insurance
      • Manufacturing
      • Retail
      • Software & Technology
      • Transportation
      • See all Solutions
      • DOCUMENTATION
      • Kong Konnect
      • Kong Gateway
      • Kong Mesh
      • Kong AI Gateway
      • Kong Insomnia
      • Plugin Hub
      • EXPLORE
      • Blog
      • Learning Center
      • eBooks
      • Reports
      • Demos
      • Customer Stories
      • Videos
      • EVENTS
      • AI + API Summit
      • Webinars
      • User Calls
      • Workshops
      • Meetups
      • See All Events
      • FOR DEVELOPERS
      • Get Started
      • Community
      • Certification
      • Training
      • COMPANY
      • About Us
      • Why Kong?
      • We're Hiring!
      • Press Room
      • Investors
      • Contact Us
      • PARTNER
      • Kong Partner Program
      • SECURITY
      • Trust and Compliance
      • SUPPORT
      • Enterprise Support Portal
      • Professional Services
      • Documentation
      • Press Releases

        Kong Names Bruce Felt as Chief Financial Officer

        Read More
  • Pricing
  • Login
  • Get a Demo
  • Start for Free
Blog
  • AI Gateway
  • AI Security
  • AIOps
  • API Security
  • API Gateway
|
    • API Management
    • API Development
    • API Design
    • Automation
    • Service Mesh
    • Insomnia
    • View All Blogs
  1. Home
  2. Blog
  3. Engineering
  4. Dynamic Routing Based on JWT Token’s Claim with Kong Konnect
Engineering
November 3, 2022
5 min read

Dynamic Routing Based on JWT Token’s Claim with Kong Konnect

Shlomi Tubul

A common use case that is frequently requested is how to dynamically route requests based on authentication attributes. An example of this technique is routing requests to relevant upstream services based on claims contained in a JWT token.

Admins would like all their clients to go to the same URI as it makes the implementation easier. But behind the scenes they might need to tailor specific configuration/applications for them, hence routing their request based on their identity.

Kong Gateway is typically ran with a set of ancillary services, including a backend datastore, Kong Manager, Analytics, and Developer Portal. Traditionally, users of Kong Gateway have been required to self host these additional services to experience the full capabilities of the Kong platform.

In this post, we’ll use Kong Konnect, the new Kong SaaS API platform. Konnect hosts the Kong platform’s management capabilities (backend datastore, Kong Manager, Analytics, Developer Portal, and more) in a multi-cloud environment. This frees the customer from managing these ancillary services and allows them to focus on hosting the data planes (aka, proxy runtimes) and building their business logic.

As we’ve seen in a previous blog post, Kong thrives in routing requests dynamically. However, in this post, we’ll take things a step further by dynamically routing requests based on the authentication process.

While we’re going to be covering everything using Konnect, it’s important to highlight that you can use the same procedure below in your own self-managed environment, as the same configuration applies to all deployments.

To start, let’s outline the prerequisites:

  1. A Konnect account and a connected runtime. This is documented in the Get started with Konnect page, steps 1 and 2.
  2. A Konnect personal access token (PAT). To generate the token, log in to your account, click on your username, then “Personal access token”, then press the “Generate token” button. (See figure 1 below.)
  3. decK, installed locally, decK is a tool used to declaratively configure Kong Gateway. Using decK with Kong Konnect contains the instructions for connecting your local decK installation to your Konnect account.
  4. 3rd party Identity Provider (IdP). For this demo, I am using Keycloak. I’ve set up two users that will access the "/bank" route in our proxy port. The user bob will use the "great-discount" bank and suzy will use the "low-interest" bank. This off course can be implemented with any Identity provider support oauth2 you are using.

Figure 1

High Level Architecture

For our example use case, we are managing a banking application that serves different bank's customers.

In my example , all customers go to the same service address (http://kong.bankingservice.com) which is basically a DNS entry where the Kong service resides. Within Kong we will have the following configured:

  • A service — A representation of our application
  • A route — A route will let you expose how a service is being requested.

During our demo, we will show how we can route 2 requests that sent to the same route to 2 different paths based on authentication properties.

For our use case, we will use the authentication mechanism to determine which path needs to be used, based on the JWT claims of the authenticated user. The claim we’ll use will be labeled “bank”. An architectural diagram of the scenario is shown below:

Here is an example of a JWT token. The “bank” attribute contains the information we will use to route the request.

Setup

To make things easier to identify, we’ll create a simple web application that will just print the path of the requested URL. This will allow us to see where exactly the user has been redirected.

To make things as simple as possible, we’ll use a simple python script that creates a web server and prints the path. This python script is shown below:

#!/usr/bin/env python3
"""
Very simple HTTP server in python for logging requests
Usage::
    ./server.py [<port>]
"""
from http.server import BaseHTTPRequestHandler, HTTPServer
import logging
import re

class S(BaseHTTPRequestHandler):
    def _set_response(self):
        self.send_response(200)
        self.send_header('Content-type', 'text/html')
        self.end_headers()

    def do_GET(self):
        logging.info("GET request,\nPath: %s\nHeaders:\n%s\n", str(self.path), str(self.headers))
        self._set_response()
        bank = str(self.path).split('/')[-1].split('?')[0]
        self.wfile.write( """<html>
                            <head>
                              <title>Title</title>
                            </head>
                            <body>
                              <h2>Welcome To {bank} Bank</h2>
                              <p>Complete path is {self.path} </p>
                            </body>
                            </html>""".format(**locals()).encode('utf-8'))

def run(server_class=HTTPServer, handler_class=S, port=8080):
    logging.basicConfig(level=logging.INFO)
    server_address = ('', port)
    httpd = server_class(server_address, handler_class)
    logging.info('Starting httpd...\n')
    try:
        httpd.serve_forever()
    except KeyboardInterrupt:
        pass
    httpd.server_close()
    logging.info('Stopping httpd...\n')

if __name__ == '__main__':
    from sys import argv

    if len(argv) == 2:
        run(port=int(argv[1]))
    else:
        run()

To test our app , we can just run it:

./http.server.py 8080
INFO:root:Starting httpd...

Once the app is running, we can look at our browser (with the address of the local server) to see how it works:

So as we haven’t put our application behind Kong and the OIDC authentication, there is no bank name yet.

Implement configuration to Kong GW

To bulk load the Kong configuration, we will use a tool called decK, which will enable us to configure our complete setup with just one call.

For our use case, the declarative file (demo-deployment.yaml) looks as follows:

_format_version: "1.1"
_info:
  defaults: {}
  select_tags:
  - bank-demo-service
_konnect:
  runtime_group_name: <your konnect runtime group>
services:
- connect_timeout: 60000
  enabled: true
  host: <host of your service>
  name: bank-demo-service
  path: /bank
  port: 8080
  protocol: http
  read_timeout: 60000
  retries: 5
  tags:
  - bank-demo-service
  write_timeout: 60000

  plugins:
  - name: request-transformer-advanced
    config:
      replace:
        uri: /bank/$(headers['bank'])
  - name: openid-connect
    config:
      issuer: <your issuer config path>
      client_id:
      - <your client id>
      client_secret:
      - <client secret>
      ssl_verify: false
      redirect_uri:
      - http://<your GW address>/bank/*
      upstream_headers_claims:
      - bank
      upstream_headers_names:
      - bank

routes:

- name: bank-demo-route
  service:
    name: bank-demo-service
  paths:
  - /bank
  strip_path: true

There are a couple of notes to highlight from our YAML file:

  • We created a service named "bank-demo service" which basically represents our backend application which is the simple python application.
  • We created a route with the path /bank to allow access to the service.
  • We attached the openid-connect plugin to the bank service. The plugin is configured to integrate with a keycloak demo instance. We have also transformed the "bank" claim in the JWT token to a header attribute, for routing purposes.
  • We attached the request-transformer-advanced plugin to replace the backend url with a new one that consists with the value of the "bank" header.\

To completely configure the gateway, we need one simple decK command:

deck sync --konnect-addr https://us.api.konghq.com --konnect-email <your konnect email> --konnect-token <konnect personal access token> --konnect-runtime-group-name <your runtime group> --state demo-deployment.yaml

For additional info on how to use decK with our Konnect Cloud offer, you can follow Kong's official documentation.

If we want to take a look on how this implementation looks in konnect UI:

Now, let’s test our application.

When we try to access our service through the runtime instance (in my case running locally on my laptop), we are redirected to keycloak for authentication. The first user we will try is Bob:

And the result is:

Now lets try with our other user, Suzy:

And the result is similar, but we are redirected to a new URL, as it was expected:

Summary

In this blog, we saw how easy it is to leverage Kong in order to create complex dynamic routing based on specific attributes (in this case, JWT token's claims).

All users have the same Login process, and according to their attributes they are routed to the relevant application/path for their service. This makes the maintenance of the deployed application much easier and cleaner.

In this demo, we used Kong’s Konnect (SaaS) which makes deployment and maintenance much easier. As Kong can be deployed in the vast majority of architectures (on-prem, cloud, hybrid, docker, k8s, etc), you can reproduce these capabilities no matter which form you choose.

Ready to try Kong Konnect?

Accelerate your journey to microservices, secure and govern APIs and services, and boost developer productivity with Kong Konnect, the easiest way to get started with Kong Enterprise

Start a Free Trial >

Developer agility meets compliance and security. Discover how Kong can help you become an API-first company.

Get a DemoStart for Free
Kong KonnectJWTAPI Authentication

More on this topic

Videos

Okta and Kong Konnect Part 4: Access Control Policies

Videos

Okta and Kong Konnect Part 3: Introspection Flow

See Kong in action

Accelerate deployments, reduce vulnerabilities, and gain real-time visibility. 

Get a Demo
Topics
Kong KonnectJWTAPI Authentication
Shlomi Tubul

Recommended posts

How to Craft and Sign a Custom JWT in Kong Konnect

EngineeringJune 18, 2024

The JSON Web Token (JWT) is an open standard that allows information to be transferred securely between different parties. The token is digitally signed by using a private key (HMAC) or a public/private key (RSA) by building a JSON Web Signature (JW

Jerome Guillaume

How JWT Authentication Works for Microservices: API Gateway Tutorial

EngineeringFebruary 16, 2021

As you build and maintain more applications, your authentication strategy becomes increasingly important. It may also be top of mind for your boss since technology leaders cited "improve application security" as one of their top priorities in this y

Marco Palladino

Secure AI at Scale: Prisma AIRS and Kong AI Gateway Now Integrated

EngineeringFebruary 9, 2026

In today's digital landscape, APIs are the backbone of modern applications, and AI is the engine of innovation. As organizations increasingly rely on microservices and AI-powered features, the API gateway has become the critical control point for man

Tom Prenderville

Modernizing Integration & API Management with Kong and PolyAPI

EngineeringFebruary 9, 2026

The goal of Integration Platform as a Service (iPaaS) is to simplify how companies connect their applications and data. The promise for the first wave of iPaaS platforms like Mulesoft and Boomi was straightforward: a central platform where APIs, sys

Gus Nemechek

AI Voice Agents with Kong AI Gateway and Cerebras

EngineeringNovember 24, 2025

Kong Gateway is an API gateway and a core component of the Kong Konnect platform . Built on a plugin-based extensibility model, it centralizes essential functions such as proxying, routing, load balancing, and health checking, efficiently manag

Claudio Acquaviva

Farewell Ingress NGINX: Explore a Better Path Forward with Kong

EngineeringNovember 14, 2025

"To prioritize the safety and security of the ecosystem, Kubernetes SIG Network and the Security Response Committee are announcing the upcoming retirement of Ingress NGINX . Best-effort maintenance will continue until March 2026. Afterward, there w

Justin Davies

Kong Konnect Adds Support for Federated Authentication

Product ReleasesSeptember 1, 2022

Our latest release of Kong Konnect augments the security and compliance of the offering through enhanced authentication capabilities. Through the rest of this post, we’ll walk you through each of these features and explore what’s new in this Kong

Hayden Lam

Ready to see Kong in action?

Get a personalized walkthrough of Kong's platform tailored to your architecture, use cases, and scale requirements.

Get a Demo
Powering the API world

Increase developer productivity, security, and performance at scale with the unified platform for API management, AI gateways, service mesh, and ingress controller.

Sign up for Kong newsletter

    • Platform
    • Kong Konnect
    • Kong Gateway
    • Kong AI Gateway
    • Kong Insomnia
    • Developer Portal
    • Gateway Manager
    • Cloud Gateway
    • Get a Demo
    • Explore More
    • Open Banking API Solutions
    • API Governance Solutions
    • Istio API Gateway Integration
    • Kubernetes API Management
    • API Gateway: Build vs Buy
    • Kong vs Postman
    • Kong vs MuleSoft
    • Kong vs Apigee
    • Documentation
    • Kong Konnect Docs
    • Kong Gateway Docs
    • Kong Mesh Docs
    • Kong AI Gateway
    • Kong Insomnia Docs
    • Kong Plugin Hub
    • Open Source
    • Kong Gateway
    • Kuma
    • Insomnia
    • Kong Community
    • Company
    • About Kong
    • Customers
    • Careers
    • Press
    • Events
    • Contact
    • Pricing
  • Terms
  • Privacy
  • Trust and Compliance
  • © Kong Inc. 2026