Skip to main content

Enterprise-grade authentication for microservices with Kong and Keycloak integration

Project description

Auth Gate

Enterprise-grade authentication for microservices with Kong and Keycloak integration.

Features

  • Dual-mode authentication: Support for both Kong header-based auth (production) and direct Keycloak validation (development)
  • Service-to-service authentication: Built-in client credentials flow for secure inter-service communication
  • Circuit breaker pattern: Resilient handling of Keycloak failures with automatic recovery
  • FastAPI integration: Ready-to-use dependencies for protecting endpoints
  • Role-based access control: Fine-grained permission management with role and scope validation
  • Middleware support: Automatic request authentication with configurable exclusions

Installation

pip install auth-gate

For Development

pip install auth-gate[dev]

Quick Start

Basic Usage

from fastapi import FastAPI, Depends
from auth_gate import (
    AuthMiddleware,
    get_current_user,
    require_admin,
    UserContext,
    AuthSettings
)

# Initialize FastAPI app
app = FastAPI()

# Add authentication middleware
app.add_middleware(
    AuthMiddleware,
    excluded_paths={"/health", "/metrics"},
    excluded_prefixes={"/docs", "/openapi.json"}
)

# Protected endpoint - requires authentication
@app.get("/api/profile")
async def get_profile(user: UserContext = Depends(get_current_user)):
    return {
        "user_id": user.user_id,
        "username": user.username,
        "roles": user.roles
    }

# Admin-only endpoint
@app.get("/api/admin/users")
async def list_users(admin: UserContext = Depends(require_admin)):
    return {"message": "Admin access granted"}

# Role-based access
from auth_gate import require_roles

require_supplier_or_admin = require_roles("supplier", "admin")

@app.get("/api/products")
async def list_products(user: UserContext = Depends(require_supplier_or_admin)):
    return {"products": []}

Service-to-service Auth

from auth_gate import ServiceAuthClient
import httpx

# Get service auth client
auth_client = ServiceAuthClient()

# Make authenticated service call
async def call_other_service():
    # Get service token (automatically cached and refreshed)
    auth_header = await auth_client.get_service_token()

    async with httpx.AsyncClient() as client:
        response = await client.get(
            "http://other-service/api/data",
            headers={"Authorization": auth_header}
        )
        return response.json()

Configuration

Configure via envirinment variables:

# Authentication mode
AUTH_MODE=kong_headers  # or "direct_keycloak", "bypass" (testing only)

# Keycloak settings
KEYCLOAK_REALM_URL=https://keycloak.example.com/realms/tradelink
KEYCLOAK_CLIENT_ID=my-service
KEYCLOAK_CLIENT_SECRET=secret

# Service account (for S2S auth)
SERVICE_CLIENT_ID=my-service-account
SERVICE_CLIENT_SECRET=secret

# Optional settings
VERIFY_HMAC=false
INTERNAL_HMAC_KEY=your-hmac-key

Advanced Features

Custom Excluded Paths

app.add_middleware(
    AuthMiddleware,
    excluded_paths={"/health", "/metrics", "/public"},
    excluded_prefixes={"/static", "/docs"},
    optional_auth_paths={"/api/products"}  # Auth optional for these paths
)

Direct Validator Usage

from auth_gate import UserValidator, AuthMode

validator = UserValidator(mode=AuthMode.DIRECT_KEYCLOAK)
user_context = await validator.validate_keycloak_token(token)

Circuit Breaker Configuration

The S2S auth client includes automatic circuit breaker protection:

  • Opens after 5 consecutive failures
  • Attempts recovery after 60 seconds
  • Provides fail-fast behavior when Keycloak is unavailable

Development

Running Tests

pytest tests/ --cov=auth_gate

Code quality

black src/
ruff check src/
mypy src/

License

For use within tradelink suite of services - See LICENSE file for details.

Support

For issues and questions, please use the GitHub issue tracker.

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

auth_gate-0.1.0.tar.gz (25.5 kB view details)

Uploaded Source

Built Distribution

If you're not sure about the file name format, learn more about wheel file names.

auth_gate-0.1.0-py3-none-any.whl (30.2 kB view details)

Uploaded Python 3

File details

Details for the file auth_gate-0.1.0.tar.gz.

File metadata

  • Download URL: auth_gate-0.1.0.tar.gz
  • Upload date:
  • Size: 25.5 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/6.2.0 CPython/3.13.7

File hashes

Hashes for auth_gate-0.1.0.tar.gz
Algorithm Hash digest
SHA256 1733d98fba34807db26cfade358f4523384f6aca2346549a2772e562a7304fd1
MD5 19801ecfb5b829d12a831a6b284640fc
BLAKE2b-256 f8e5f60f21dbfd60ea99d7dafb68f9fe18b10785979449a662a89809500eb43b

See more details on using hashes here.

File details

Details for the file auth_gate-0.1.0-py3-none-any.whl.

File metadata

  • Download URL: auth_gate-0.1.0-py3-none-any.whl
  • Upload date:
  • Size: 30.2 kB
  • Tags: Python 3
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/6.2.0 CPython/3.13.7

File hashes

Hashes for auth_gate-0.1.0-py3-none-any.whl
Algorithm Hash digest
SHA256 b29d7ea17f10703bf486f6e5ac41a4b559b4b6ec0bfa4063b6525f836c99017d
MD5 886381cff10009723ba60f2acbf3be3e
BLAKE2b-256 d4d2ef99e15993cc8e51f0296c05cacbf04701c26df8c8e5f84ee711685c776a

See more details on using hashes here.

Supported by

AWS Cloud computing and Security Sponsor Datadog Monitoring Depot Continuous Integration Fastly CDN Google Download Analytics Pingdom Monitoring Sentry Error logging StatusPage Status page