Using Keycloak as a Reverse Proxy for 3rd Party API Authentication

Abstract: Resolve confusion by implementing Keycloak as an OAuth 2.0 identity provider for server-to-server API authentication instead of a generic reverse proxy.

Created: 2026-10-08 by

Keycloak does not function as a generic reverse proxy for authenticating outbound requests to third-party APIs. Instead, it acts as an identity provider that issues tokens via OAuth 2.0 or OpenID Connect. To authenticate server-to-server calls, your application must act as an OAuth client, obtain an access token from Keycloak, and include it in the API request headers.

Understanding the Architecture

The core misunderstanding in many architectural diagrams is treating Keycloak as a network-level proxy like Nginx or HAProxy. Keycloak is a software-based Identity Provider (IdP). It manages users, realms, clients, and roles. When you need to call a third-party API, your backend service (the "client") needs proof of identity. Keycloak provides this proof by issuing JSON Web Tokens (JWTs) after validating credentials. This approach separates concerns. Your application logic handles business rules, while Keycloak handles authentication and authorization. This pattern is known as the Authorization Code Grant flow or the Client Credentials Grant flow, depending on whether there is an interactive user involved. For pure server-to-server communication, the Client Credentials Grant is the standard choice because it requires no human interaction. You can read more about managing user sessions in Trigger Automatic Logins/Logouts for Users on Multiple Websites Connected with Keycloak, which shares underlying session management concepts relevant to token lifecycle handling.

Configuring the Client in Keycloak

Before writing code, you must configure Keycloak to recognize your application as a trusted client. This involves creating a new client within the appropriate Realm. Navigate to the Clients section in the Admin Console and select Create. Enter a Client ID that identifies your application, such as my-backend-service. Set the Client Type to OpenID Connect. The most critical setting here is the Access Type. For server-to-server authentication, set the Access Type to Confidential. This ensures that the client secret is kept secure on your server and not exposed to browsers or mobile devices. Next, configure the Valid Redirect URIs. While this field is primarily used for browser-based flows, some implementations require at least one entry to pass validation. You can use https://localhost as a placeholder if no UI redirect is needed. Ensure that the Standard Flow is disabled if you are strictly using the Client Credentials grant, although leaving it enabled does not harm security in this context. Save the configuration. Note down the Client ID and generate a new Secret. These two values are required for your application to authenticate with Keycloak's token endpoint.

Implementing Token Acquisition

Your backend service must now implement the logic to request an access token. This is typically done using an HTTP POST request to the Keycloak token endpoint. The URL format is generally /realms/{realm-name}/protocol/openid-connect/token. The request body must contain several parameters:
  • grant_type: Set this to client_credentials for server-to-server auth.
  • client_id: The ID you created in the previous step.
  • client_secret: The secret generated for that client.
  • scope: Optional. Specify the resources or permissions your API needs.
If you are using a language like Java or Python, libraries exist to handle this automatically. For example, Spring Security provides auto-configuration for Keycloak. If you are using raw HTTP, ensure you handle the response correctly. A successful response returns a JSON object containing the access_token, refresh_token, and expiration time. It is crucial to cache these tokens. Requesting a new token for every single API call introduces latency and increases load on Keycloak. Implement a simple cache with a TTL slightly shorter than the token's expiration time. When the token expires, refresh it silently before making the next request. For deeper insights into connecting your application infrastructure, see Troubleshooting Java Connect Exception: Connection Refused in Docker Compose Spring Boot Keycloak, which addresses common networking issues when your app talks to Keycloak.

Using the Token with the Third-Party API

Once you have the access token, passing it to the third-party API is straightforward. Most modern APIs expect authentication via the HTTP Authorization header. Construct the header value as Bearer {access_token}. Example cURL command:
curl -X GET https://api.thirdparty.com/data \
-H "Authorization: Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9..."
Ensure that the third-party API accepts JWTs signed by Keycloak. Some APIs require specific claims within the token, such as a custom audience claim or a specific scope. You may need to configure Mappers in Keycloak to inject these claims into the token payload. Go to the Client settings in Keycloak, select Mappers, and add a new mapper to include necessary attributes.

Security Best Practices

Never expose the client secret in frontend code or version control. Store it in environment variables or a secrets manager. Use HTTPS everywhere. Keycloak should be configured to enforce TLS, and your internal services should validate certificates if they are self-signed during development. Regularly rotate your client secrets. Keycloak allows you to regenerate secrets without downtime. Update your application configuration immediately after rotation. Monitor Keycloak logs for failed login attempts, which could indicate brute-force attacks against your client credentials.

Frequently Asked Questions

Can I use Keycloak as a direct HTTP proxy?

No, Keycloak is not designed to forward HTTP traffic like Nginx or Apache. It processes authentication protocols and returns tokens. You must use a separate reverse proxy if you need load balancing or SSL termination for your API endpoints.

What happens if the Keycloak server goes down?

Your application will fail to obtain new tokens. If you have cached valid tokens, existing requests might succeed until they expire. However, once all cached tokens expire, your service will stop functioning until Keycloak is restored.

How do I handle token expiration gracefully?

Implement a retry mechanism. When the third-party API rejects a request with a 401 Unauthorized error, invalidate the local token cache, fetch a fresh token from Keycloak, and retry the original request.

Can I restrict API access to specific users?

Yes, but this requires the Authorization Code Grant flow instead of Client Credentials. In that case, the user logs in interactively, and the resulting token contains their user identity and roles, which your API can check before granting access.

Why am I getting a 401 error from Keycloak?

This usually means the client ID or secret is incorrect, or the realm name in the token URL is wrong. Verify your credentials in the Keycloak Admin Console and ensure the URL matches the exact realm identifier.

Latest News

How to Display Output of xterm Command in Terminal Screen using Cron

Resolve the inability to display xterm output in a terminal screen from cron by redirecting logs or using wall instead of insecure X11 workarounds.

Read More
Expose Local Server on VPS Preserving Real Client IPs (OS Level)

Resolve VPS logging showing only gateway IPs by configuring reverse proxies to forward real client addresses via X-Forwarded-For headers.

Read More
How to Clear Recent Files History in Linux without Deleting Actual Files?

Clear recent files history in Linux by deleting ~/.local/share/recently-used.xbel without removing the actual files.

Read More
Best HDD Copy Strategy: Manually Syncing and Rewriting Scratch

Resolve data drift between two 4TB hard drives by using rsync with the --delete flag to manually sync and rewrite scratch data for an exact mirror.

Read More
Understanding Bash Prompt Abbreviations: An Overview

Resolve repetitive typing errors by creating and persisting Bash aliases in the .bashrc file for improved command-line efficiency.

Read More
Free Tools and Methods to Log Real-Time Performance Details in Task Manager

Log real-time CPU and memory metrics to CSV files using Windows Performance Monitor Data Collector Sets to troubleshoot system slowness.

Read More
Contact Qatar Airways Customer Service: Phone Number, Help Center, and More

Resolve urgent Qatar Airways reservation issues like flight changes and baggage claims using the US phone number +1801-855-5905 or online self-service tools.

Read More
Windows 11: Alt Codes Displaying Wrong Characters - Solutions

Resolve Windows 11 Alt codes showing wrong characters by verifying the US keyboard layout and enabling Num Lock.

Read More
Run Programs with Elevated Privileges: A Comprehensive Guide

Eliminates the need to type sudo for frequent administrative tasks by configuring .bashrc aliases or functions.

Read More
Dynamically Changing Dates in Excel Formulas Using Cells

Eliminate manual date updates in Excel by using cell references to create dynamic formulas that automatically adjust calculations when input dates change.

Read More
Granting Edit Access to a Specific Excel Sheet in an Office 365 User Email ID-Based Login

Excel Online lacks native sheet-level permissions, so users must split workbooks or use worksheet protection to isolate edit access for specific tabs.

Read More
Creating Network Load on Local Wi-Fi from One PC

Generate sustained Wi-Fi bandwidth load from a single PC using a VM SFTP server to test router stability and throughput.

Read More
Changing the Default Editor for Batch Files in Windows 11's File Explorer

Resolve the issue of batch files opening in Notepad by changing the default editor to a preferred application like VS Code.

Read More
Gain WiFi Connection Minutes Before Losing it by Changing MAC Address

Bypass MAC address filtering to restore WiFi connectivity temporarily when a device is blocked by network administrators.

Read More
Photos Folders Turned Black: Troubleshooting Picture Applications on Windows

Resolve black screens in Windows Photos by resetting the app, updating graphics drivers, and repairing system files.

Read More
Troubleshooting High CPU Temperature Values: A Step-by-Step Guide

Resolve high CPU temperatures and thermal throttling by monitoring with Speedfan, cleaning dust from cooling components, and replacing degraded thermal paste.

Read More
Make cURL establish TLS connection with CA unknown

Resolve cURL TLS connection failures with unknown or self-signed certificates by using the --insecure flag to bypass CA validation.

Read More
Troubleshooting Incorrect Network Metrics Values in Grafana, Prometheus, InfluxDB, and Telegraf

Fix incorrect network metrics in Grafana, Prometheus, InfluxDB, and Telegraf by verifying interface selection, resolving unit mismatches, and handling counter resets.

Read More
Start Another Terminal Window (cmd.exe) Windows Repair/Troubleshoot

Provides step-by-step instructions to access the Windows Command Prompt via bootable media for advanced system repair and troubleshooting.

Read More
Thinkpad P1 Gen 6: Sudden Thunderbolt 3 Dock USB-C Charging Stopped Working

Resolve sudden Thunderbolt 3 dock USB-C charging and internet failure on ThinkPad P1 Gen 6 by updating firmware, resetting the dock, and adjusting power settings.

Read More
ASUS Windows 11 Laptop: Internet Connection Issue with Hotspot

Resolve ASUS Windows 11 laptop spinning wheel issue when connecting to mobile hotspot by resetting network stack, disabling IPv6, and adjusting power settings.

Read More
Developing iOS Project with Firebase: Logging in and Sending Push Notifications

Integrates Firebase to enable secure user authentication and push notifications in iOS applications.

Read More
Troubleshooting Bash Script with Suspected Issues of Spaces, Dashes, Filenames and Quoting

Resolve Bash script failures caused by word splitting, globbing, and special characters in filenames by applying proper quoting techniques.

Read More
Populating OneDrive Folder for Local Backup without Affecting Remote Files

Prevent OneDrive from deleting remote files during Windows reinstallation by unlinking the account or using symbolic links to isolate local data.

Read More
Force First Frame as Keyframe Without Re-encoding: A Quick Solution

Resolve inaccurate seeking and playback glitches by re-encoding video to ensure the first frame is a valid keyframe.

Read More
Find Information in Database Using WSL (Ubuntu) on Windows-10

Resolve database connection issues from WSL Ubuntu on Windows 10 by configuring client tools and network access to query remote or local servers.

Read More
Configuring a New Router with Different Networks: One Family, One Guest

Resolve IP conflicts and isolate guest traffic by configuring a second router with a distinct subnet via its WAN port.

Read More
Quickly Open Multiple Stock Websites with a Single Command

Solve the problem of manually opening multiple stock research websites by creating a single command to launch them simultaneously on Windows, macOS, or Linux.

Read More
Improved Adobe Acrobat Search Experience: Access Advanced Search with Ease

Access advanced search filters like case sensitivity and regex in Adobe Acrobat by clicking More Options in the Find bar.

Read More
Port Forwarding VM via OpenVPN: A Comprehensive Guide

Configure OpenVPN server and iptables to forward specific ports from VPN clients to a virtual machine's internal IP address.

Read More
Understanding Partitions in the 1980s: A Look Back at MS-DOS and Master Boot Record

Explains how the Master Boot Record and partition table enabled MS-DOS to manage multiple disk volumes on a single physical drive.

Read More
Windows 10 Enterprise: Keyboard Not Detected in Managed Organization with Admin Privileges

Resolve Windows 10 Enterprise keyboard detection failures caused by Group Policy restrictions, driver corruption, or USB enumeration errors.

Read More
Can't Find x86_64 Versions of Applications on MacOS arm64 (M1)

Resolve missing x86_64 app issues on M1 Macs by installing Rosetta 2 and reinstalling apps as universal binaries.

Read More
How to Hide Installation Source for an Android App

Manage Android app installation source visibility by using USB transfers or file managers to reduce browser traces and isolate data via work profiles.

Read More
Connecting Momentus 4200.2 ST9808210A Hard Drive via USB Cable

Resolve inability to access Seagate Momentus 4200.2 ST9808210A hard drive by connecting it via USB using a compatible SATA-to-USB adapter and configuring the disk in Windows.

Read More