Protecting apps behind Apache HTTP Server with mod_auth_openidc

Put Keycloak sign-in in front of legacy web apps at the Apache HTTP Server layer, choose mod_auth_openidc or mod_auth_mellon, and pass identity to the app safely.

On this page

How Apache HTTP Server protects a legacy app with Keycloak login

Apache HTTP Server can enforce Keycloak sign-in in front of a legacy app by loading mod_auth_openidc for OpenID Connect or mod_auth_mellon for SAML. The module redirects anonymous visitors to Keycloak, validates the tokens or assertions that come back, keeps a session, and only then forwards the request to the application along with the authenticated user's identity. The application's own code does not need to implement login, which is why this approach suits apps that have no modern authentication, no maintained library, or source code your team no longer controls.

Two decisions matter more than the rest. The first is the module choice. OIDC through mod_auth_openidc matches how Keycloak clients are configured today, with a confidential client, authorization code flow and a redirect URI registered in the realm, while SAML through mod_auth_mellon fits applications or partners that already speak SAML 2.0. Confirm the module versions you plan to run against the Keycloak release in your environment, because the Apache packages and the Keycloak release move on separate schedules. The second is the header design. The app will trust whatever Apache passes in headers such as the user name, email or group claims, so the header names, the claims they come from and the way the app reads them must be agreed before build starts.

Plan for the app to be reachable only through Apache. If clients can reach the application server directly, they can send forged identity headers and bypass the login gate, so network rules, bind addresses or a dedicated internal network must enforce the path. Also confirm with your security team how session lifetime, logout and token refresh behave for this app, since the module manages those at the Apache layer, not inside the application. Ask the implementation partner or your own team to document each header, its source claim and the test that proves a request without a valid session is refused.

What you need before you configure Apache and Keycloak

Protecting a legacy app at the Apache layer touches four systems: the Keycloak realm, the Apache server, the mod_auth_openidc module, and the app behind it. Confirm each one before writing any configuration, because the module version, the Apache packaging and the Keycloak release all constrain what you can set up.

Keycloak release and database

Record the Keycloak release you will run and the production database behind it. The current release is 26.8.1, but your target may differ, so confirm the version you have approved against the upgrade notes. Confirm the database is one Keycloak supports for production, such as PostgreSQL 14 to 18, rather than the development file database. The database choice affects which upgrade path and high availability design you can use later.

Keycloak database docs

Apache HTTP Server version and packaging

Identify the Apache HTTP Server version on the legacy host and whether it comes from your operating system packages, a vendor build, or a container image. Packaging decides where the module comes from, how it is patched, and whether you can install it without rebuilding Apache. Confirm the Apache version is still receiving security fixes from its source, since an unpatched front end becomes the entry point for every app behind it.

mod_auth_openidc version and release notes

Choose the mod_auth_openidc release and read its release notes before you deploy. Notes describe changes to session handling, configuration directives and supported OpenID Connect features, which affect your settings. Check the module's documentation for the Apache versions it supports rather than assuming that your installed Apache is covered. Pin the module version so a routine package update does not change authentication behavior on a live host.

TLS certificates for the public hostname

Obtain a valid certificate for the public hostname that users reach on the legacy app, and confirm the chain is trusted by the browsers your users run. Keycloak's production guide calls for TLS on all communication, so the Keycloak frontend and the Apache site both need certificates. Decide who renews them and how renewal is monitored, because an expired certificate blocks every sign-in at once.

Keycloak production guide

Network paths to Keycloak

Map two addresses before configuration: the frontend URL that browsers use for redirects, and the backchannel URL that Apache uses to fetch discovery metadata, exchange codes and validate tokens. These can differ, for example when Apache reaches Keycloak over an internal name. Confirm firewall rules and DNS allow both paths, and that the Keycloak admin console is not reachable through the public frontend hostname.

Named owner for the legacy app

Name one owner who decides which users may reach the app, which claims the app expects in headers, and how sign-out and session timeouts should behave. The app itself may not have been written to trust identity headers, so the owner must confirm which header names it reads and whether it validates them. Without a named owner, nobody can sign off on the claim mapping or approve changes after go-live.

How a request flows through Apache, Keycloak and the app

The flow starts when a browser requests a protected path on the public side of Apache. The module finds no session, redirects the browser to Keycloak, and the user signs in there. Keycloak returns an authorization code to the module, which validates the tokens over the back channel and sets identity headers before Apache proxies the request across the boundary to the app. Check that the app network accepts traffic only from the Apache host, and that clients cannot send their own identity headers.

Apache with mod_auth_openidc gates the app and passes identity in headers.

Choosing mod_auth_openidc or mod_auth_mellon for the legacy app

Choose mod_auth_openidc when the legacy application can sit behind Apache and you control the Keycloak realm enough to register an OpenID Connect client. The module runs the authorization code flow at the Apache layer, so the application does not handle the login redirect or the password prompt itself. Registration is usually the simpler path when the same team owns both the Apache host and the realm.

  • Confidential client. Create the client in the Keycloak realm with client authentication turned on, so Apache holds a client secret that never reaches the browser. Store the secret in the Apache configuration with restricted file permissions, not in the application repository.
  • Redirect URI. Register the exact callback URL on the Keycloak client, built from the public Apache hostname and the path set in OIDCRedirectURI. A mismatch between the two values is the most common cause of a failed first login.
  • Provider metadata. Point OIDCProviderMetadataURL at the realm's OpenID configuration so the module reads endpoints and signing keys from Keycloak instead of from values copied by hand.
  • Identity to the application. Map the user name and group claims into request headers through the module's claim settings, and strip any client-supplied header with the same name at the edge so the application can trust what Apache sends.
  • Session and logout. Decide how the Apache session ends and whether a Keycloak logout call is made, and coordinate that choice with your single logout design.

Confirm the directive names, supported OIDC features and minimum Apache version in the mod_auth_openidc documentation before you write the configuration.

How to configure the Keycloak client and Apache module in order

This sequence takes a legacy web app from no login to a working Keycloak sign-in at the Apache layer, with identity passed to the app in headers and access limited to the protected location. Each step ends with a check you can run before moving on.

  1. Confirm or create the realm

    Decide whether the app uses an existing realm or a dedicated one. A dedicated realm keeps the app's users, login settings and client policies separate from other applications. Your Keycloak administrator makes the change in the admin console, and the check is that the realm's OpenID Endpoint Configuration page loads over HTTPS from the Apache host's network path. If you reuse a shared realm, record which users and groups can reach the app before you continue.

  2. Register a confidential client for the Apache host

    Create an OIDC client with client authentication turned on, the standard authorization code flow, and a redirect URI that points to the Apache host's callback path on the protected site, using the exact HTTPS hostname users type. Store the client secret in your secrets manager, not in a web-accessible file. The check is a client settings page showing the redirect URI and the secret saved, with no wildcard redirect URIs left in place.

  3. Set scopes and mappers for the app's claims

    Limit the client's default scopes to the ones the app needs, usually openid, profile and email, and add protocol mappers only for claims the app reads, such as a username, mail address or group membership. Keep the list short so that headers passed to the app stay small and predictable. The check is a decoded test token, taken from the client's Client scopes evaluate tool or a test login, that contains exactly the claims you planned.

  4. Install mod_auth_openidc and set provider metadata

    Install the mod_auth_openidc module on the Apache host from your operating system's package source or the project's build, then load it in the Apache configuration. Set the issuer to your realm's URL, let the module read provider metadata from the discovery document, and supply the client ID and secret from the secrets store. The check is a clean configuration test of Apache and a request to the protected path that redirects to the Keycloak login page.

  5. Configure session, cookie and logout settings

    Set the session lifetime, the inactivity timeout, the cookie attributes (Secure, HttpOnly and a SameSite value your login flow supports), and a logout path on the protected site. Keep the Apache session store on a path all Apache workers can reach if you run more than one server. Align the access token lifetime in Keycloak with how long you want a stale session to last. The check is a successful login, a session cookie that carries the Secure and HttpOnly flags in the browser, and a logout that returns the user to the login page.

  6. Map identity headers to the proxied app

    Tell the module which claims to send to the application as request headers, such as the remote user and group values, and make sure the application reads only these headers. Strip any incoming header with the same names from the client request so that users cannot forge identity. The check is a test page or request log in the app that shows the expected header values for a test user, and a request with a forged header that the app ignores.

  7. Restrict the protected location

    Scope the module to the protected path with a location or directory block and require a valid authenticated session there, using the module's claim or group checks where the app needs role-based access. Confirm the unprotected paths, such as health checks or static assets you intend to leave open, are listed explicitly. The check is a request to a protected path without a session that redirects to login, and a request with a user who lacks the required group that receives a denial.

  8. Confirm the Keycloak and Apache limits

    Before go-live, record the Keycloak version and the mod_auth_openidc version you tested, and confirm the support boundaries with your Keycloak distribution and the module's documentation. Check that the Keycloak admin console is reachable only on its own hostname or path, as Keycloak's production guide recommends. The check is a written test record covering login, logout, header values, denied access and admin endpoint exposure, signed off by the team that will operate the setup.

Mapping Keycloak claims to headers the app reads

This table compares each Keycloak claim or attribute with an illustrative header name, the token or userinfo source it comes from, and the application field it feeds. Header names are set in the Apache configuration, so treat the examples as placeholders and confirm every directive against the mod_auth_openidc documentation before you rely on it. The main takeaway is that every header the app trusts must come from a claim you control, and any inbound header with the same name must be stripped first.

Keycloak claim or attributeExample header name (illustrative)SourceApp field it feeds
Subject (sub)OIDC_CLAIM_subID token, stable per user in the realmInternal user key; never use as a display name
Username (preferred_username)OIDC_CLAIM_preferred_usernameID token or userinfo, from the user profileLogin name shown in the app and audit logs
Email (email)OIDC_CLAIM_emailID token or userinfo, requires the email claim in the client scopeAccount lookup or notification address; check whether the app matches on it
Display name (name)OIDC_CLAIM_nameID token or userinfo, from first and last name attributesGreeting and user profile display
Group membershipOIDC_CLAIM_groupsGroup membership mapper added to the client scope by your Keycloak administratorsApp role or access decision; mapper contents must be approved before go-live
Realm or client rolesOIDC_CLAIM_roles (illustrative)Role mapper; realm roles and client roles appear in different claim pathsApp role mapping; confirm the claim path in your Keycloak token before writing rules
Tenant or organization identifierOIDC_CLAIM_org (illustrative)Only if the Organizations feature or a custom attribute is configured in your realmTenant scoping in multi-customer apps; omit if the app is single tenant

Security settings that keep identity headers trustworthy

In this pattern, Apache decides who the user is and the application trusts the headers it receives. Every card below protects that trust: if a client can forge a header, reach the app directly, or keep a session alive after logout, the identity the app sees is wrong. Check each setting in your own environment before the app goes live.

Enforce TLS on every hop

Keycloak's production guide calls for TLS on all communication. For this pattern that means three links: the browser to Apache, Apache to Keycloak for the authorization code exchange and metadata fetches, and Apache to the backend app. Confirm that mod_auth_openidc validates the Keycloak certificate chain against a trusted CA bundle and that the redirect URI uses https. Plaintext on any hop lets an attacker read or replace the tokens that feed the headers.

Keycloak production guide

Strip client-supplied identity headers

Apache must remove any identity header a client sends before mod_auth_openidc sets its own values. Otherwise a user can send a forged header such as a user name or group claim, and the app will accept it. Check the configuration so the header unset or equivalent step runs for every identity header name your app reads, and test by sending a request with a spoofed header while logged out and logged in. The app should see only the values Apache set.

Restrict the app to Apache traffic

Headers are only trustworthy if Apache is the only path to the app. Bind the application to localhost or a private interface, or enforce network rules so only the Apache host can connect. Confirm that no other load balancer, ingress or sidecar can reach the backend port. Test by calling the backend directly with the identity headers set: the request should fail.

Set session lifetimes and cookie flags

mod_auth_openidc keeps the user's session in an encrypted cookie or a server-side cache, and the session lifetime controls how long a logged-in user keeps the headers. Decide the idle timeout and maximum session length with your security team, and align them with the access token lifespan set on the Keycloak realm. Confirm the session cookie is marked Secure and HttpOnly, and that the session store is shared correctly if Apache runs on more than one node.

Separate admin and public hostnames

Keycloak's production guide advises exposing the admin console and Administration REST API on a different hostname or context path from public frontend URLs. Apache should proxy only the public login paths for this integration and must not expose the admin console through the same virtual host. Confirm the proxy rules deny the admin paths and that the frontend URL set in Keycloak matches the public hostname Apache serves.

Keycloak production guide

Validate backchannel logout handling

When a user signs out in Keycloak, Keycloak sends a backchannel logout token to registered clients. Confirm that your mod_auth_openidc version handles the logout endpoint and ends the local Apache session, so the headers stop being issued. Keycloak 26.8 requires signature validation of backchannel logout tokens from external providers, so check that the Apache side also validates the token. Test by signing out in Keycloak and confirming the next request to the app is redirected to login.

Where Keycloak's support limits end and your team's work begins

Keycloak's documentation covers the protocols, client settings and production configuration that the Keycloak project publishes, including the Keycloak server administration guide. The Apache module that sits in front of your application, mod_auth_openidc or mod_auth_mellon, is a separate third-party component with its own maintainers, release cycle and issue tracker. Keycloak's guidance does not extend to defects in that module, to its Apache HTTP Server integration or to how it handles sessions and headers. Before the build starts, your team should treat the Apache layer as a distinct dependency with its own owner, not as part of the Keycloak platform.

Confirm four things in writing before go-live. First, the exact module name and version each Apache host will run, pinned in your package or container build rather than left to the operating system's default. Second, who answers for a module defect: your internal platform team, a vendor or support contract for the module if one exists, or a partner under a retainer. Third, what a Keycloak upgrade changes for the client settings the module depends on, such as redirect URIs, client authentication method, scopes, signing algorithms and the claims used for headers. Keycloak's upgrading guide is the place to check those changes for each target release.

Test every module upgrade and every Keycloak upgrade against the same set of checks: a full login and logout through Apache, session expiry and refresh, a request to each protected path, the header values received by the application, and a rejected request for a user without the required group or role. Keep the test results with the change record so the next reviewer can see what was verified and against which versions. No vendor certifies this combination of Keycloak, Apache HTTP Server and the module, so your own test evidence is what shows it works in your environment.

Common failures when Apache sits in front of Keycloak

This table pairs the failures teams most often hit when mod_auth_openidc sits in front of Keycloak with their likely causes and fixes. Read each row starting from the symptom you see, then check the module and Keycloak logs for the exact messages before changing settings. Most of these failures trace back to a mismatch between the URLs Apache advertises and the URLs Keycloak has registered.

SymptomLikely causeFix
Browser loops between Apache and KeycloakThe redirect URI registered in the Keycloak client does not match the URI mod_auth_openidc sends, often because Apache sees http behind a TLS-terminating proxySet the public scheme and host on the proxy and Apache, make OIDCRedirectURI match the registered value exactly, and confirm the forwarded headers reach Apache
Login returns an invalid redirect or state errorVirtual host name or port differs from the one used at registration, or the cookie domain does not cover the requested hostUse one canonical hostname for the app, register that exact redirect URI, and check the OIDCCookieDomain and OIDCCookie settings
Module rejects the provider with an issuer mismatchThe issuer in the discovery document does not equal the configured issuer, usually because the realm URL differs by hostname or path from the one Keycloak publishesCopy the issuer from the realm's well-known OpenID configuration and use it unchanged in the module settings, including the realm path
Metadata or discovery fetch fails at startupApache cannot reach the Keycloak discovery endpoint, or the metadata URL points at an internal name that the public configuration does not resolveTest the discovery URL from the Apache host, fix DNS or routing, and confirm the endpoint is reachable from the backend network
TLS errors when Apache calls Keycloak's token or JWKS endpointsApache does not trust the certificate chain Keycloak presents, often because an internal certificate authority is missing from the trust store used by the moduleAdd the issuing CA to the trust store the module uses, verify the full chain, and avoid disabling verification as a workaround
Identity headers are empty or missing in the applicationThe claim named in the header directive is not in the ID or access token, because the client mapper was not configured or the scope was not requestedAdd a protocol mapper for the claim in the Keycloak client scope, request that scope in the module, and confirm the claim appears in a test token
Tokens rejected as not yet valid or expired immediatelyClock skew between the Apache host and Keycloak, so the iat, nbf or exp checks failSynchronize both hosts with NTP, check time zones and drift, and confirm the module's allowed clock tolerance before changing token lifetimes
User is signed in on one request and asked to log in again on the nextSession cookies are not shared across load balancer nodes or are lost behind sticky-session misconfigurationEnable a shared session store that the module supports, or configure consistent routing, and confirm the cookie reaches every node
Logout clears the Apache session but the app still shows the user as signed inThe application keeps its own session or cache, and the front-channel or back-channel logout path never reaches itClear the application session on logout, review the module's logout URL settings, and test logout end to end; see the Keycloak single logout guidance for limits
Log messages do not match these symptomsLog level, module version or Keycloak configuration differs from the environment this table assumesConfirm the exact messages in the module's error log and Keycloak's server log for your versions before applying a fix

Questions teams ask before protecting a legacy app with Apache and Keycloak

What drives the effort of protecting a legacy app behind Apache with Keycloak?

The main drivers are the number of protected paths, how the app uses identity headers, and how many environments need the same setup. Each path that needs a different rule (public, logged in, or restricted to a group) adds configuration and testing. An app that reads user identity from headers needs those headers mapped carefully, and the app's own session and authorization logic must be checked so it does not trust a header a user could forge. Every environment (development, test, staging, production) needs its own client settings, redirect URIs and certificates, so the count multiplies the verification work. Ask the partner to list paths, headers and environments in the written scope before pricing.

Can our own team protect a legacy app with mod_auth_openidc in-house?

Often yes, if the team already runs Apache HTTP Server, understands OpenID Connect and can test login and logout end to end. The hard parts are less the module setup than the verification: confirming that unauthenticated requests never reach the app, that headers cannot be spoofed past the proxy, that logout clears the Apache session, and that the Keycloak client is locked down. Teams without that experience usually spend the most time on those checks. A partner can take the whole job or only the review and hardening step, and the split should be written into the scope.

What do we need to provide from the app owner and the network team?

The app owner must describe which URLs are public, which need login, and which roles or groups may reach them. They must also say which headers the app reads, whether it has its own login or session, and how it handles logout. The network team must confirm the DNS names, TLS certificates, firewall rules between Apache, Keycloak and the app, and whether a load balancer sits in front of Apache. Both teams should agree on who owns the Keycloak realm and client settings, because those changes affect every app that uses them.

How does the choice between OIDC and SAML and the number of apps change the time needed?

mod_auth_openidc covers OpenID Connect with Keycloak, and mod_auth_mellon covers SAML 2.0. Both need the same kind of work: a client or SAML client in Keycloak, a module configuration on Apache, header mapping and tests. The protocol changes the configuration details and the metadata exchange, so a team that already runs one protocol usually finds the other slower to set up. Each additional app adds its own paths, headers and environments, so the time grows with the app count more than with the protocol. Shared patterns, such as one realm and reusable Apache snippets, reduce repeated work when the apps are similar.

What recurs after go-live, such as module upgrades, Keycloak upgrades and certificate renewal?

Several tasks recur. Apache packages and mod_auth_openidc need patching, and the module version must stay compatible with the Apache release in use. Keycloak releases are published on a regular cycle, and its upgrade notes can change behavior, so client settings and login flows need retesting after each upgrade. TLS certificates for the Apache hosts and the Keycloak hostname expire and need renewal. Session cookie settings, the client secret and the signing keys may also need rotation under your security policy. Ask the partner for a written list of these tasks and who performs each one.

What should we ask for in a written quote for this work?

Ask for a scope that lists each protected application, its paths, the headers it needs, the protocol, and the environments in scope. The quote should name the Apache, mod_auth_openidc or mod_auth_mellon and Keycloak versions it targets, and state which Keycloak and Apache changes are covered if versions move during the work. Ask which deliverables you receive, such as configuration files, a test report, a runbook and knowledge transfer. Clarify what is one-time and what is a recurring retainer for upgrades, testing and support. DeployOpen does not publish a price list, and most engagements are fixed-scope with scope, deliverables and timelines agreed in writing before work starts.

Does Keycloak support every legacy app behind Apache, and what are its limits?

Keycloak supports OpenID Connect, OAuth 2.0 and SAML 2.0, so the login step works for apps reached through Apache with either module. The limits sit in the application. An app that cannot accept identity from headers, or that expects its own password store, may need a change or a different pattern. Keycloak's production guidance also expects TLS everywhere and a reverse proxy with path restrictions, so the Apache layer must fit that design. Confirm the app's header and session behavior early, because that is the most common reason a legacy integration needs rework.

How DeployOpen scopes and delivers Keycloak protection for legacy apps

DeployOpen plans and delivers Keycloak login in front of legacy web apps at the Apache HTTP Server layer, with mod_auth_openidc for OIDC or mod_auth_mellon for SAML. The work is scoped in writing before it starts, built in your own infrastructure, and handed over with documentation your team can run.

How we scope

  • Inventory each legacy app, its hostnames, paths, and whether it can trust identity headers safely.
  • Agree in writing which protocol, mod_auth_openidc or mod_auth_mellon, fits each application and its session needs.
  • Define which claims map to headers, which paths stay public, and which roles gate access.

How we build

  • Configure the Apache HTTP Server virtual hosts, the Keycloak client, and redirect URIs for each protected app.
  • Strip any incoming identity headers at the proxy so clients cannot spoof them, then test that behavior directly.
  • Test login, logout, session expiry, and access denial for each path, using your own test accounts and environments.

How we hand over

  • Deliver configuration files, client settings, and a runbook covering certificate rotation and session timeouts.
  • Document the support limits Keycloak states for this pattern so your team knows what the vendor will and will not cover.
  • Walk your operations and application teams through the header contract each app receives and how to change it.

How we support

  • Engagements are fixed-scope, with scope, deliverables, and timelines agreed in writing before work starts.
  • Ongoing support, upgrades, and continuous security testing are available as a retainer after handover.
  • Ask any proposal to confirm how Apache, mod_auth_openidc and Keycloak upgrades will be tested before rollout.

Sources and further reading

Talk to our team.

Tell us what you're working on, whether it's a deployment, an audit, a security test or a cyber range. You'll speak with an engineer who can help you scope it.

  • 30-minute call: free, with no obligation.
  • NDA on request: we can sign before you share details.
  • Clear next steps: a scope and plan after the call.