System Architecture: Move Authentication to the API Gateway

When exposing an application to the outside world, consider a Reverse-Proxy or an API Gateway to protect it from attacks. Rate Limiting comes to mind first, but it shouldn’t stop there. We can factor many features in the API Gateway and should be bold in moving them from our apps. In this post, I’ll show how to implement authentication at the Gateway API stage.

Overall authentication flow

The API Gateway doesn’t authenticate but delegates authentication to an authentication provider. After authentication, the Gateway forwards the request to the app. The app checks authentication and gets the associated identity and permissions.

Now, onto the implementation. We will implement the above flow with the following components:

Keycloak for the Identity Provider
Apache APISIX for the API Gateway
The Spring ecosystem for developing the app


Keycloak is a feature-rich Open Source identity provider:

Add authentication to applications and secure services with minimum effort. No need to deal with storing users or authenticating users.

Keycloak provides user federation, strong authentication, user management, fine-grained authorization, and more


Keycloak offers the realm abstraction, a namespace to group logically-related objects. We will first create an apisix Realm to our configuration from other configurations. The official documentation explains how to do it in great detail. We can proceed further with creating objects under the apisix realm.

The next step is to create an OpenID client for Apache APISIX to call Keycloak in the apisix realm. Here are the data:

General settings:

Client type: OpenID Connect
Client ID: apisix

Capability config:

Client authentication: ON

Go to the Credential tab and note the client’s secret value.

The final step is to create users. A user is a person who can log in to the system to access the app. Let’s create two users, john and jane, and set their passwords. The demo repository already has Keycloak pre-configured – both users’ password is doe.

Spring Security

We secure our application via Spring Security.

Here are the required dependencies:

<artifactId>spring-boot-starter-security</artifactId> <!–1–>
<artifactId>spring-boot-starter-oauth2-client</artifactId> <!–2–>

Protect the application
Call the Keycloak server

The protecting code uses Spring Security:

bean {
ref<HttpSecurity>().authorizeHttpRequests {
it.requestMatchers(“/*”) //1
.hasAuthority(“OIDC_USER”) //1
}.oauth2Login {} //2

Any request requires to have the OIDC_USER authority
“Log in” via OAuth2

The next step is configuring the framework:
client-id: apisix #1
authorization-grant-type: authorization_code
scope: openid
issuer-uri: http://localhost:9009/realms/apisix #2
user-name-attribute: preferred_username #3

Use the client created in Keycloak. We pass the secret at runtime via an environment variable
Keycloak realm to use. We override the domain in the Docker compose file via an environment variable
Use the user name instead of the token for display purposes

I’ll use a dummy Thymeleaf page to display the logged-in user. We need additional dependencies:

<artifactId>thymeleaf</artifactId> <!–1–>
<artifactId>thymeleaf-spring6</artifactId> <!–2–>
<artifactId>thymeleaf-extras-springsecurity6</artifactId> <!–3–>

Thymeleaf proper
Thymeleaf and Spring integration
Offers dedicated Spring Security tags

The view is the following:

<!doctype html>
<html lang=”en” xmlns:sec=””>
<h1>Welcome to My App</h1>
<span sec:authentication=”name”>Bob</span> <!–1–>

Display the “name” of the logged-in user


Lastly, let’s configure the entry point into our system. I assume you’re familiar with this blog and don’t need an introduction to Apache APISIX. If you do, feel free to look at the APISIX, an API Gateway the Apache way.

In standalone mode, the configuration file is the following:

– uri: /*
“myapp:8080”: 1
discovery: http://keycloak:9009/realms/apisix/.well-known/openid-configuration #1
client_id: apisix #2
client_secret: rjoVkMUDpUH4TE7IXhhJuof4O7OFrbph
bearer_only: false
scope: openid
realm: apisix #3
redirect_uri: http://localhost:9080/callback #4

Keycloak offers an endpoint that details every necessary endpoint for an OpenID integration
Use the same client as the app. In real-world scenarios, we should use one client per component, but it’s a demo
Use the realm created in the Keycloak section
Any URL that’s a subpath of the protected URL will do

Putting it all together

We put everything together via Docker Compose:

image: apache/apisix:3.4.0-debian
– ./config/apisix/config.yml:/usr/local/apisix/conf/config.yaml:ro #1
– ./config/apisix/apisix.yml:/usr/local/apisix/conf/apisix.yaml:ro #2
– “9080:9080”
– /bin/bash
– -c
– |
/opt/keycloak/bin/ import –file /opt/keycloak/data/import/keycloak.json –override true #3
/opt/keycloak/bin/ start-dev –http-port 9009 #4
– ./config/keycloak:/opt/keycloak/data/import:ro
– “9009:9009”
build: ./myapp
– keycloak
restart: on-failure #8

Configure standalone mode
Routes and plugins configuration as seen in the previous section
Initialize Keycloak with the existing saved realm
Start Keycloak
Configure the OAuth client
Because the flow is browser-based, we will be redirected to a keycloak domain for authentication. Hence, we have to update our /etc/hosts with a new keycloak entry
Set Spring Security log level to debug helps understand issues
Spring Security eagerly tries to contact Keycloak. Keycloak takes a while to initialize itself; we need to let the app crash and start again until Keycloak is ready

Let’s try to access the application via Apache APISIX. When we browse to , Apache APISIX redirects us to the Keycloak login page:

If we log in successfully, we are allowed to access the app. Notice that we display the username of the person who logged in:


In this post, we described how to move the authentication step to the API Gateway stage, delegate authentication to an identity provider, and let the app verify the authentication status.

We implemented it with Apache APISIX, Keycloak, and Spring Security.

Many other options are available, depending on your environment.

The complete source code for this post can be found on GitHub.

To go further:

Keycloak Administration Guide
How to Integrate Keycloak for Authentication with Apache APISIX
A Quick Guide to Using Keycloak With Spring Boot

Originally published at A Java Geek on July 30th, 2023

The post System Architecture: Move Authentication to the API Gateway appeared first on foojay.