Skip to content

n2k/authlord

Repository files navigation

AuthLord

Multi-Tenant OAuth2 Authentication Proxy

A lightweight, high-performance OAuth2 reverse proxy written in Go that supports multiple tenants, providers, and integrates seamlessly with nginx's auth_request module. Perfect for SaaS platforms, white-label applications, and enterprise authentication.

Features

  • Landlord & Tenant Admin: Global admin plus per-tenant self-service admin
  • 15+ OAuth Providers: Google, GitHub, GitLab, Azure AD, Okta, Auth0, AWS Cognito, Discord, Slack, Apple, Facebook, Twitter/X, Bitbucket, Generic OIDC
  • Multi-Site Support: Unlimited tenants with independent configuration
  • Auto-Setup Sites: Drop credential files into a directory for automatic site provisioning
  • Secure Session Management: Cookie-based (stateless) or Redis-backed sessions
  • Hot Config Reload: Automatic file watching or manual API reload without restart
  • Modern Admin UI: Dark/light themes, responsive design, full CRUD operations
  • Advanced Configuration: Environment variables, file loading, modular configs, secret manager integration
  • Docker Ready: Multi-stage Docker build with minimal footprint (<25MB)
  • High Performance: Stateless architecture, optional Redis for scale
  • nginx Integration: Native support for nginx auth_request module
  • Rate Limiting: Per-IP rate limiting on all auth endpoints (10k verify/min, 1k login/min)
  • Prometheus Metrics: Full observability with Prometheus-format metrics
  • Request Tracing: Request ID propagation for distributed tracing
  • API Keys: Machine-to-machine authentication with scoped access
  • Email Notifications: Login alerts, security events, API key management
  • Token Refresh: Automatic OAuth token renewal for 9+ providers
  • Custom Branding: Per-tenant logos, colors, and themes
  • Session Management UI: View and revoke active sessions
  • Webhook Events: Login, logout, session revoked, config changed, access denied
  • OpenAPI Spec: Complete API documentation in OpenAPI 3.0.3 format

Screenshots

Dashboard - Sites

Dashboard - Sites

Providers Tab

OAuth Providers Management

Site Configuration

Site Configuration

Quick Start

1. Clone and Setup

git clone <your-repo-url>
cd authlord
cp config.example.json config.json

2. Configure OAuth Providers

Google OAuth2

  1. Go to Google Cloud Console
  2. Create a new project or select existing
  3. Enable "Google+ API"
  4. Go to "Credentials" → "Create Credentials" → "OAuth 2.0 Client ID"
  5. Set authorized redirect URIs: https://your-domain.com/auth/callback
  6. Copy Client ID and Client Secret to config.json

GitHub OAuth2

  1. Go to GitHub Developer Settings
  2. Click "New OAuth App"
  3. Set Authorization callback URL: https://your-domain.com/auth/callback
  4. Copy Client ID and Client Secret to config.json

3. Edit Configuration

# Generate cookie secret
./authlord secret

# Edit config.json with your OAuth credentials

See config.example.json for a complete configuration template.

4. Run with Docker Compose

docker compose up -d --build
# for dev
docker compose --profile dev up

The proxy will be available at http://localhost:8080

5. Access Admin UI

Navigate to http://localhost:8080/admin/

OAuth-based access (recommended):

  • You'll be redirected to OAuth provider login
  • After authentication, access is granted if your email is in allowed_emails

See docs/ADMIN_SETUP.md for detailed setup instructions.

Nginx Integration

Example nginx.conf

server {
    listen 443 ssl;
    http2 on;
    server_name app.example.com;

    ssl_certificate /etc/nginx/ssl/app.example.com.crt;
    ssl_certificate_key /etc/nginx/ssl/app.example.com.key;

    # AuthLord endpoints (must come BEFORE protected locations)
    location /auth/ {
        proxy_pass http://authlord:8080;
        proxy_set_header Host $host;
        proxy_set_header X-Real-IP $remote_addr;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_set_header X-Forwarded-Proto $scheme;
        proxy_set_header X-Forwarded-Host $host;
    }

    # Protected application
    location / {
        # AuthLord OAuth Protection
        auth_request /auth/verify;
        error_page 401 = @error401;
        
        # Capture user info
        auth_request_set $user $upstream_http_x_auth_request_user;
        auth_request_set $email $upstream_http_x_auth_request_email;
        proxy_set_header X-User $user;
        proxy_set_header X-Email $email;
        
        # Forward to backend
        proxy_pass http://backend:3000;
        proxy_set_header Host $host;
        proxy_set_header X-Real-IP $remote_addr;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_set_header X-Forwarded-Proto $scheme;
    }

    # Handle 401 errors - redirect to login
    location @error401 {
        return 302 https://auth.example.com/auth/login?site=app.example.com&rd=https://$host$request_uri;
    }
}

CRITICAL: The /auth/ location must come BEFORE the protected / location to prevent redirect loops on OAuth callback.

See docs/NGINX.md for comprehensive nginx configuration examples.

Key Features

Multi-Tenant Architecture

Each site (tenant) operates independently with:

  • Separate OAuth providers or shared providers
  • Independent access control (email/domain whitelists)
  • Custom branding and pages
  • Per-tenant session configuration
  • Optional self-service tenant admin access

See docs/MULTI_TENANT.md for detailed multi-tenant guide.

Tenant Admin Access

Give enterprise customers admin access to manage their own tenant without accessing other tenants:

{
  "sites": [{
    "id": "acme-corp",
    "domain": "acme.example.com",
    "tenant_admin_mode": true,
    "tenant_admins": ["admin@acmecorp.com"],
    "allowed_domains": ["acmecorp.com"]
  }]
}

Tenant admins can manage access control, customize pages, and configure OAuth scopes for their site.

See docs/TENANT_ADMIN.md for complete tenant admin guide.

API Keys (Machine-to-Machine Auth)

Create API keys for backend services and automation:

# Create via Admin UI or Tenant Admin UI
# Or via API:
curl -X POST http://localhost:8080/tenant-admin/sites/my-site/api-keys \
  -H "Cookie: session_cookie" \
  -d '{
    "name": "Backend Service",
    "description": "Production API access",
    "scopes": ["read", "write"]
  }'

Use API keys in your applications:

curl -H "Authorization: Bearer authlord_key_xxxxx" \
  https://app.example.com/api/data

See docs/API_KEYS_USAGE.md for usage guide with code examples.

Email Notifications

Automated security notifications for:

  • Login alerts (new login from known or new device)
  • API key created/revoked alerts
  • Security events

Configurable SMTP settings with customizable HTML/plain text templates.

See docs/EMAIL_NOTIFICATIONS.md for setup and customization.

Session Management

View and manage active sessions:

  • List all active sessions per site *
  • View session details (device, location, last activity) *
  • Revoke individual sessions *
  • Bulk revoke all sessions *
  • Supports both cookie and Redis session stores

*Redis session store is optional but required for these features.

See docs/REDIS_SESSIONS.md for Redis configuration.

Custom Branding

Per-tenant customization:

  • Custom logos (light/dark mode)
  • Brand colors and themes
  • Custom login/logout/error pages
  • Favicon customization

See docs/BRANDING.md for branding guide.

Token Refresh

Automatic OAuth token renewal for maintained access to provider APIs:

  • Automatic refresh before expiration
  • Non-blocking, transparent to users
  • Supports 9+ providers (Google, GitHub, Azure AD, Okta, Auth0, etc.)
  • Configurable refresh timing

See docs/TOKEN_REFRESH.md for details.

Configuration

Basic Configuration

{
  "listen_address": ":8080",
  "admin_enabled": true,
  "admin_auth": {
    "allowed_emails": ["admin@example.com"],
    "require_oauth": true,
    "admin_provider_id": "google-provider",
    "admin_cookie_name": "_oauth2_admin",
    "admin_cookie_secret": "your-32-char-secret"
  },
  "sites": [
    {
      "id": "my-app",
      "domain": "app.example.com",
      "provider_id": "google-provider",
      "cookie_secret": "your-32-char-secret",
      "allowed_domains": ["example.com"]
    }
  ],
  "providers": [
    {
      "id": "google-provider",
      "type": "google",
      "client_id": "xxx.apps.googleusercontent.com",
      "client_secret": "your-secret",
      "redirect_url": "https://app.example.com/auth/callback"
    }
  ]
}

Advanced Configuration

AuthLord supports powerful configuration features:

Environment Variables:

{
  "client_secret": "$ENV['OAUTH_SECRET']"
}

File Loading (Docker Secrets, K8s Secrets):

{
  "client_secret": "/run/secrets/oauth-secret",
  "allowed_emails": "/etc/authlord/users.txt"
}

Modular Configuration:

{
  "include": [
    "./config/providers.json",
    "./config/sites/*.json",
    "/etc/authlord/tenants"
  ]
}

See docs/CONFIGURATION.md for comprehensive configuration guide.

API Endpoints

Authentication

  • GET /auth/verify - nginx auth_request endpoint
  • GET /auth/login?rd=/path - Initiate OAuth login
  • GET /auth/callback - OAuth callback handler
  • GET /auth/logout?rd=/path - Logout

Admin API

All admin endpoints require authentication (OAuth or Basic Auth).

Sites:

  • GET /admin/api/sites - List sites
  • POST /admin/api/sites - Create site
  • GET /admin/api/sites/:id - Get site
  • PUT /admin/api/sites/:id - Update site
  • DELETE /admin/api/sites/:id - Delete site

Providers:

  • GET /admin/api/providers - List providers
  • POST /admin/api/providers - Create provider
  • GET /admin/api/providers/:id - Get provider
  • PUT /admin/api/providers/:id - Update provider
  • DELETE /admin/api/providers/:id - Delete provider

Sessions:

  • GET /admin/api/sites/:id/sessions - List active sessions
  • DELETE /admin/api/sites/:id/sessions/:session_id - Revoke session

API Keys:

  • GET /tenant-admin/sites/:id/api-keys - List API keys
  • POST /tenant-admin/sites/:id/api-keys - Create API key
  • PUT /tenant-admin/sites/:id/api-keys/:key_id/revoke - Revoke API key
  • DELETE /tenant-admin/sites/:id/api-keys/:key_id - Delete API key

Health Checks

  • GET /health - Health check endpoint
  • GET /health/live - Liveness probe
  • GET /health/ready - Readiness probe

Metrics

  • GET /metrics - Prometheus metrics endpoint

Includes:

  • Authentication metrics (verify, login, callback success/failure by site)
  • HTTP request counters by method and status
  • Request duration percentiles (p50, p95, p99)
  • Active users gauge per site
  • Rate limiter statistics

CLI Commands

authlord validate    # Validate configuration file
authlord secret      # Generate secure cookie secret
authlord health      # Health check (for Docker healthcheck)
authlord version     # Show version info
authlord help        # Show help

See docs/API.md for complete API reference.

Development

Build from Source

# Install dependencies
go mod download

# Build
go build -o authlord cmd/authlord/main.go

# Run
./authlord

Run Tests

go test ./...

Build Docker Image

docker build -t authlord:latest .

Performance

Expected Performance:

  • Auth verification: <1ms
  • OAuth callback: <200ms
  • Admin API: <10ms
  • Memory usage: <30MB
  • Binary size: ~15MB
  • Container size: ~25MB

Security

  1. HTTPS Required: Always use HTTPS in production
  2. Strong Secrets: Use cryptographically secure random secrets (32+ bytes)
  3. Cookie Security: Cookies are encrypted, signed, and marked HttpOnly/Secure
  4. OAuth State: CSRF protection via state parameter
  5. Admin Access: Protect admin UI with OAuth or strong credentials
  6. Email Verification: Providers check verified_email

See docs/ADMIN_SECURITY.md for security best practices.

Documentation

Getting Started

Configuration & Features

Admin & API

Architecture & Monitoring

Troubleshooting

OAuth Errors

"redirect_uri_mismatch"

  • Ensure redirect URL in config matches OAuth app settings exactly
  • Include protocol (https://) and path (/auth/callback)

"Email not verified"

  • User must verify their email with the provider

Session Issues

Sessions not persisting

  • Check cookie_secret is consistent
  • Verify browser accepts cookies
  • Ensure Secure flag works (requires HTTPS)

nginx Integration

401 errors on every request

  • Verify /auth/ location is properly configured
  • Check authlord is accessible from nginx
  • Ensure Host header is forwarded correctly

Contributing

Contributions are welcome! Please read the contributing guidelines before submitting PRs.

License

MIT License - see LICENSE file for details.

Support

  • Documentation: docs/
  • Issues: GitHub Issues
  • Discussions: GitHub Discussions

Credits

AuthLord - Multi-Tenant OAuth2 Authentication Proxy

Built with:

About

No description, website, or topics provided.

Resources

Stars

0 stars

Watchers

0 watching

Forks

Releases

No releases published

Packages

 
 
 

Contributors