Keycloak OAuth2-Proxy Configuration Generator: with our main partner Please-Open.It we strongly advocate the use of authentication proxy pattern. As we mentioned in our authentication proxy article, this architectural approach is one of the most efficient ways to secure applications without modifying their code. While we developed our own NGINX-based solution for complex scenarios, we recognize that OAuth2-Proxy is often the perfect choice for many use cases, especially in containerized environments.

The challenge: Setting up OAuth2-Proxy requires carefully transcribing client credentials and OIDC endpoints from Keycloak into configuration files or environment variables—a manual, error-prone process. That’s why we built a Keycloak SPI extension that automatically generates OAuth2-Proxy configurations directly from your Keycloak clients.

Project: https://github.com/please-openit/keycloak-oauth2proxy-client-installation-provider

Why OAuth2-Proxy

The Right Tool for Many Scenarios

OAuth2-Proxy is a lightweight, battle-tested reverse proxy that provides authentication for web applications. It’s particularly well-suited for:

  • Containerized environments: Docker, Kubernetes, Docker Compose
  • Microservices architectures: Protect multiple services with a single authentication gateway
  • Internal tools and dashboards: Add authentication to services that don’t natively support it
  • Cloud-native deployments: Minimal resource footprint and excellent scalability

Complementary to Our Authentication Proxy

In our authentication proxy article, we presented our NGINX + OpenResty solution with advanced features like custom interstitial pages, fine-grained URL rules, and complex claim transformations. Both solutions serve the same purpose but excel in different contexts:

  • Our NGINX solution: Best for complex requirements, custom logic, advanced claim manipulation
  • OAuth2-Proxy: Perfect for straightforward authentication needs, rapid deployment, and standard OIDC flows

Many of our clients use OAuth2-Proxy for the majority of their services and reserve our custom solution for specific edge cases. The key is having both options available.

The Configuration Challenge

Manual Configuration is Tedious

Setting up OAuth2-Proxy with Keycloak typically involves:

  1. Creating a client in Keycloak
  2. Copying the client ID and secret
  3. Finding the correct OIDC issuer URL
  4. Constructing redirect URLs
  5. Generating cookie secrets
  6. Writing configuration files or environment variables
  7. Testing and debugging inevitable typos

This process is repetitive, error-prone, and time-consuming when you’re securing multiple applications.

Configuration Drift

As teams grow and projects multiply, configuration management becomes complex:

  • Different team members use different formats
  • Subtle variations in configuration lead to debugging sessions
  • Security parameters might be inconsistently applied
  • Updates to Keycloak endpoints require manual updates everywhere

Our Solution: Automatic Configuration Generation

A Keycloak SPI Extension

We developed a Keycloak Service Provider Interface (SPI) extension that adds OAuth2-Proxy configuration export directly into the Keycloak admin console. The extension provides two export formats, accessible from the client’s “Installation” tab.

Two Export Formats

1. Environment Variables Format (.env file)

Perfect for containerized deployments where configuration via environment variables is the norm:

OAUTH2_PROXY_PROVIDER="keycloak-oidc"
OAUTH2_PROXY_CLIENT_ID="my-application"
OAUTH2_PROXY_CLIENT_SECRET="your-generated-secret"
OAUTH2_PROXY_OIDC_ISSUER_URL="https://keycloak.example.com/realms/production"
OAUTH2_PROXY_REDIRECT_URL="https://app.example.com/oauth2/callback"
OAUTH2_PROXY_SCOPE="openid email profile"

# Additional optional variables (commented with examples)
# OAUTH2_PROXY_EMAIL_DOMAINS="example.com"
# OAUTH2_PROXY_COOKIE_SECURE="true"
# OAUTH2_PROXY_COOKIE_SAMESITE="lax"
# OAUTH2_PROXY_SET_XAUTHREQUEST="true"
# OAUTH2_PROXY_PASS_ACCESS_TOKEN="true"

2. Complete Configuration File (.cfg file)

A fully documented configuration file with step-by-step instructions, security best practices, and examples:

## OAuth2 Proxy Configuration File
## Generated from Keycloak for client: my-application

# Required: OpenID Connect Provider
provider = "keycloak-oidc"

# Required: Client credentials from Keycloak
client_id = "my-application"
client_secret = "your-generated-secret"

# Required: OIDC Issuer URL (Keycloak realm)
oidc_issuer_url = "https://keycloak.example.com/realms/production"

# Required: OAuth2 callback URL (must match Keycloak Valid Redirect URIs)
redirect_url = "https://app.example.com/oauth2/callback"

# Required: OAuth2 scopes to request
scope = "openid email profile"

# Cookie configuration
# IMPORTANT: Generate with: python -c 'import os,base64; print(base64.urlsafe_b64encode(os.urandom(32)).decode())'
# cookie_secret = ""

# ... dozens of additional parameters with detailed comments

Installation and Usage

Installing the Extension

The extension works with Keycloak 26.5.0 and later:

# Build the extension
mvn clean install

# Copy to Keycloak providers directory
cp deployments/please-open.it-oauth2proxy-client-installation-provider-*.jar \
   /path/to/keycloak/providers/

# Restart Keycloak
/path/to/keycloak/bin/kc.sh start

For Docker deployments:

FROM quay.io/keycloak/keycloak:26.5.0
COPY please-open.it-oauth2proxy-client-installation-provider-*.jar /opt/keycloak/providers/

Generating Configuration

Once installed, the process is straightforward:

  1. Navigate to your Keycloak client
  2. Click on the “Installation” tab (or “Action” → “Download adapter config”)
  3. Select either:
    • “Oauth2-proxy environment variables” for .env format
    • “Oauth2-proxy configuration file” for .cfg format
  4. Download and use immediately

Deployment Examples

Docker Compose: The Simplest Path

OAuth2-Proxy excels in Docker Compose environments thanks to environment variable support:

version: '3.8'

services:
  # Your backend application
  backend:
    image: your-app:latest
    ports:
      - "9000:9000"
  
  # OAuth2-Proxy protecting your backend
  oauth2-proxy:
    image: quay.io/oauth2-proxy/oauth2-proxy:latest
    env_file:
      - oauth2proxy.env  # Generated from Keycloak!
    environment:
      # Additional runtime configuration
      - OAUTH2_PROXY_COOKIE_SECRET=${COOKIE_SECRET}
      - OAUTH2_PROXY_UPSTREAMS=http://backend:9000
      - OAUTH2_PROXY_HTTP_ADDRESS=0.0.0.0:4180
      - OAUTH2_PROXY_EMAIL_DOMAINS=*
      - OAUTH2_PROXY_COOKIE_SECURE=true
    ports:
      - "4180:4180"
    depends_on:
      - backend

That’s it! The oauth2proxy.env file generated from Keycloak contains all the OIDC-specific configuration. You only need to add runtime parameters like upstream URLs and cookie secrets.

Kubernetes: ConfigMaps Made Easy

For Kubernetes deployments, use the configuration file format:

apiVersion: v1
kind: ConfigMap
metadata:
  name: oauth2-proxy-config
data:
  oauth2proxy.cfg: |
    # Paste your generated configuration here
    provider = "keycloak-oidc"
    client_id = "my-application"
    # ... rest of generated configuration    
---
apiVersion: v1
kind: Secret
metadata:
  name: oauth2-proxy-secrets
stringData:
  cookie-secret: "your-generated-cookie-secret"
  client-secret: "your-keycloak-client-secret"
---
apiVersion: apps/v1
kind: Deployment
metadata:
  name: oauth2-proxy
spec:
  replicas: 2
  selector:
    matchLabels:
      app: oauth2-proxy
  template:
    metadata:
      labels:
        app: oauth2-proxy
    spec:
      containers:
      - name: oauth2-proxy
        image: quay.io/oauth2-proxy/oauth2-proxy:latest
        args:
          - --config=/etc/oauth2-proxy/oauth2proxy.cfg
        env:
          - name: OAUTH2_PROXY_CLIENT_SECRET
            valueFrom:
              secretKeyRef:
                name: oauth2-proxy-secrets
                key: client-secret
          - name: OAUTH2_PROXY_COOKIE_SECRET
            valueFrom:
              secretKeyRef:
                name: oauth2-proxy-secrets
                key: cookie-secret
        ports:
          - containerPort: 4180
        volumeMounts:
          - name: config
            mountPath: /etc/oauth2-proxy
      volumes:
        - name: config
          configMap:
            name: oauth2-proxy-config

Configuration Examples and Use Cases

Basic Authentication: Minimal Setup

The simplest configuration protects an entire application:

# oauth2proxy.env (generated from Keycloak)
OAUTH2_PROXY_PROVIDER="keycloak-oidc"
OAUTH2_PROXY_CLIENT_ID="simple-app"
OAUTH2_PROXY_CLIENT_SECRET="..."
OAUTH2_PROXY_OIDC_ISSUER_URL="https://keycloak.example.com/realms/myrealm"
OAUTH2_PROXY_REDIRECT_URL="https://app.example.com/oauth2/callback"

# Manual additions
OAUTH2_PROXY_UPSTREAMS=http://backend:8080
OAUTH2_PROXY_COOKIE_SECRET=...
OAUTH2_PROXY_EMAIL_DOMAINS=*

Users authenticate via Keycloak, and OAuth2-Proxy passes authenticated requests to your backend. No headers, no custom claims—just authentication.

With User Information Headers

Often, your backend needs to know who the authenticated user is. Enable header injection:

# Add to your configuration
OAUTH2_PROXY_SET_XAUTHREQUEST=true
OAUTH2_PROXY_PASS_USER_HEADERS=true
OAUTH2_PROXY_PASS_ACCESS_TOKEN=true

Your backend now receives headers like:

X-Auth-Request-User: user@example.com
X-Auth-Request-Email: user@example.com
X-Auth-Request-Preferred-Username: user
Authorization: Bearer eyJhbGciOiJSUzI1NiIsInR5cCI...

This is where the magic happens: Your application receives authenticated requests with user context, without implementing any authentication logic.

Advanced: Custom Claims and Role-Based Access

OAuth2-Proxy can inject custom claims from your OIDC tokens as headers:

# Configuration file approach
set_xauthrequest = true
pass_authorization_header = true

# Inject custom claims as headers
# Example: If your token has a "roles" claim, inject it as X-Auth-Request-Roles
# This requires OAuth2-Proxy 7.4.0+ with claim injection support

While OAuth2-Proxy’s claim injection is more limited than our NGINX-based solution, it handles common scenarios well.

Multi-Application Setup: One Proxy, Many Backends

A single OAuth2-Proxy instance can protect multiple applications:

services:
  oauth2-proxy:
    image: quay.io/oauth2-proxy/oauth2-proxy:latest
    env_file:
      - oauth2proxy.env
    environment:
      # Path-based routing to different backends
      - OAUTH2_PROXY_UPSTREAMS=http://app1:8080,http://app2:9000/api
      - OAUTH2_PROXY_COOKIE_SECRET=${COOKIE_SECRET}
  
  app1:
    image: internal-dashboard:latest
    
  app2:
    image: admin-api:latest

Both applications share the same authentication, session management, and user experience.

Skip Authentication for Specific Paths

Some endpoints (health checks, public APIs) should bypass authentication:

OAUTH2_PROXY_SKIP_AUTH_REGEX="^/health|^/public|^/api/webhook"

The generated configuration includes commented examples for this and many other scenarios.

Benefits for Existing and New Applications

Protecting Legacy Applications

One of the most powerful use cases is adding authentication to applications that don’t have it:

  • Internal tools built without authentication
  • Legacy applications where modifying code is risky or impossible
  • Third-party software you can’t change
  • Prototypes and MVPs that need quick security

Deploy OAuth2-Proxy in front of these applications, and they gain enterprise-grade authentication instantly. No code changes required.

Example: Securing a legacy metrics dashboard:

services:
  grafana:
    image: grafana/grafana:latest
    environment:
      # Disable Grafana's built-in authentication
      - GF_AUTH_ANONYMOUS_ENABLED=true
      - GF_AUTH_ANONYMOUS_ORG_ROLE=Admin
      # Grafana trusts the proxy headers
      - GF_AUTH_PROXY_ENABLED=true
      - GF_AUTH_PROXY_HEADER_NAME=X-Auth-Request-Email
  
  oauth2-proxy:
    image: quay.io/oauth2-proxy/oauth2-proxy:latest
    env_file:
      - oauth2proxy.env
    environment:
      - OAUTH2_PROXY_UPSTREAMS=http://grafana:3000
      - OAUTH2_PROXY_SET_XAUTHREQUEST=true

Grafana now uses Keycloak authentication through OAuth2-Proxy, without touching Grafana’s configuration.

Accelerating New Application Development

For new applications, the authentication proxy pattern means:

Faster Development

  • Frontend and backend teams work independently
  • No authentication code in your application
  • Simplified testing (bypass proxy in dev environments)
  • Focus on business logic, not security infrastructure

Consistent Security

  • Same authentication UX across all applications
  • Centralized security updates
  • Uniform session management
  • Single point for security audits

Deployment Flexibility

  • Switch identity providers without code changes
  • Add MFA or advanced authentication flows via Keycloak
  • Deploy to different environments with different authentication schemes
  • A/B test authentication approaches

Organizational Benefits

For DevOps Teams

  • Standardized deployment patterns
  • Reduced configuration complexity
  • Fewer security incidents due to misconfiguration
  • Easy replication across environments

For Security Teams

  • Centralized authentication policy enforcement
  • Consistent audit trails
  • Simplified compliance (all authentication goes through Keycloak)
  • Clear separation of concerns

For Development Teams

  • One less component to maintain in each application
  • Standard user context via HTTP headers
  • Simplified local development (docker-compose up and you’re ready)
  • Less authentication-related bugs

Best Practices and Tips

Client Configuration in Keycloak

For optimal OAuth2-Proxy integration, configure your Keycloak client as follows:

  1. Client Type: OpenID Connect
  2. Client Authentication: On (for confidential clients)
  3. Valid Redirect URIs:
    • https://your-domain.com/oauth2/callback
    • http://localhost:4180/oauth2/callback (for local testing)
  4. Web Origins: Add your application domain for CORS
  5. Standard Flow: Enabled
  6. Direct Access Grants: Disabled (not needed for proxy pattern)

Post-Generation Steps

After downloading the configuration:

  1. Generate a Cookie Secret:
python -c 'import os,base64; print(base64.urlsafe_b64encode(os.urandom(32)).decode())'
  1. Configure Upstreams: Set the backend service URLs
  2. Security Settings for Production:
    • OAUTH2_PROXY_COOKIE_SECURE=true (requires HTTPS)
    • OAUTH2_PROXY_COOKIE_SAMESITE=lax or strict
    • OAUTH2_PROXY_EMAIL_DOMAINS to restrict access
  3. Test the Configuration: Start with a simple setup, then add complexity

When to Use Which Format

Environment Variables (.env):

  • Docker Compose deployments
  • When combining with other environment-based configuration
  • Kubernetes with ConfigMaps
  • Serverless and cloud-native platforms

Configuration File (.cfg):

  • Traditional server deployments
  • When you need extensive inline documentation
  • Complex setups with many parameters
  • When managing configuration in Git

Comparison: OAuth2-Proxy vs Our NGINX Solution

FeatureOAuth2-Proxy + GeneratorOur NGINX Auth Proxy
Setup ComplexityVery SimpleModerate
Configuration GenerationAutomatic from KeycloakManual
DeploymentSingle containerSingle container
Resource UsageMinimalLow
OIDC SupportFullFull
Custom Claims InjectionBasicAdvanced
Fine-grained URL RulesBasic regexAdvanced Lua scripting
Interstitial PagesNoYes
Custom LogicLimitedFull Lua programming
Community SupportLargeCustom
Best ForStandard auth needsComplex requirements

Use OAuth2-Proxy when:

  • You need quick deployment
  • Standard OIDC flows are sufficient
  • You prefer widely-adopted tools
  • Configuration via environment variables fits your workflow

Use our NGINX solution when:

  • You need custom interstitial pages
  • Complex claim transformations are required
  • Advanced URL-based access control is needed
  • You want to implement custom authentication logic

Real-World Example: Microservices Platform

Let’s see a complete example protecting a microservices platform:

version: '3.8'

services:
  # Authentication proxy (single instance)
  oauth2-proxy:
    image: quay.io/oauth2-proxy/oauth2-proxy:latest
    env_file:
      - oauth2proxy.env  # Generated from Keycloak!
    environment:
      - OAUTH2_PROXY_COOKIE_SECRET=${COOKIE_SECRET}
      - OAUTH2_PROXY_UPSTREAMS=http://api-gateway:8080
      - OAUTH2_PROXY_HTTP_ADDRESS=0.0.0.0:4180
      - OAUTH2_PROXY_EMAIL_DOMAINS=example.com
      - OAUTH2_PROXY_SET_XAUTHREQUEST=true
      - OAUTH2_PROXY_PASS_ACCESS_TOKEN=true
      - OAUTH2_PROXY_SKIP_AUTH_REGEX=^/api/public|^/health
    ports:
      - "443:4180"

  # API Gateway receives authenticated requests
  api-gateway:
    image: your-gateway:latest
    environment:
      - TRUSTED_PROXY=oauth2-proxy
      - USER_HEADER=X-Auth-Request-Email
    depends_on:
      - user-service
      - order-service
      - inventory-service

  # Microservices don't handle authentication
  user-service:
    image: user-service:latest
    
  order-service:
    image: order-service:latest
    
  inventory-service:
    image: inventory-service:latest

Result: All services are protected, user information flows through headers, and you only needed to configure OAuth2-Proxy once using our generator.

Troubleshooting Common Issues

Provider Not Appearing in Keycloak

  1. Verify the JAR is in the providers/ directory
  2. Check Keycloak logs for errors during startup
  3. Ensure you restarted Keycloak after deployment

OAuth2-Proxy Returns 401/403

Common causes:

  1. Redirect URI mismatch: Must match exactly in both Keycloak and OAuth2-Proxy
  2. Email domain restrictions: Check email_domains configuration
  3. Cookie settings: Ensure cookie_secure matches your HTTPS setup
  4. Token validation: Verify oidc_issuer_url is accessible from OAuth2-Proxy

Headers Not Appearing in Backend

Ensure you enabled:

OAUTH2_PROXY_SET_XAUTHREQUEST=true
OAUTH2_PROXY_PASS_USER_HEADERS=true

And verify your backend doesn’t strip these headers.

Conclusion

The authentication proxy pattern is powerful, and OAuth2-Proxy is an excellent implementation of it. By automating configuration generation through our Keycloak SPI extension, we’ve removed one of the main friction points in deploying OAuth2-Proxy at scale.

Key Takeaways:

  • Configuration generation is automatic: No more manual transcription errors
  • Two formats for different needs: Environment variables or configuration files
  • Perfect for containerized deployments: Docker Compose and Kubernetes ready
  • Complements our NGINX solution: Use the right tool for each scenario
  • Benefits existing and new applications: Instant authentication without code changes

Whether you’re securing legacy applications, building new microservices, or standardizing authentication across your organization, this tool simplifies the process.

Try it out: https://github.com/please-openit/keycloak-oauth2proxy-client-installation-provider

And if you need more advanced features, check out our authentication proxy solution.

We believe that authentication should be simple, secure, and separate from application code. This tool is another step toward making that vision a reality.

Mathieu PASSENAUD