Skip to content

Authentik Authentication Service

Authentik is an open-source identity provider that integrates with Traefik to provide OAuth2/OIDC authentication for the infrastructure. This document covers the complete setup, configuration, and operation of the Authentik authentication system.

Overview

The Authentik service provides centralized authentication for web applications while maintaining API access patterns. It uses a dual-route strategy where browser access is protected by OAuth while API endpoints remain accessible for programmatic access.

Architecture

Service Components

The Authentik stack consists of three main components:

  1. Authentik Server (authentik.rbnk.uk)
  2. Main authentication interface and administration panel
  3. Handles OAuth flows, user management, and policy enforcement
  4. Uses PostgreSQL (supa-db) for data storage and Redis for sessions

  5. Authentik Worker

  6. Background task processor for email notifications, LDAP sync, and other async operations
  7. Shares the same configuration as the server component

  8. Authentik Proxy Outpost (auth-proxy.rbnk.uk)

  9. Separate service that handles forward authentication for Traefik
  10. Validates authentication tokens and provides user headers
  11. Deployed on dedicated subdomain for cookie domain isolation

Network Configuration

networks:
  authentik:         # Internal communication between components
  traefik_proxy:     # External access via Traefik
  supabase_internal: # Database access

Configuration

Environment Variables

Key configuration variables in /srv/dockerdata/authentik/.env:

# Core Authentication
AUTHENTIK_SECRET_KEY=your-secret-key-here
AUTHENTIK_HOST=https://authentik.rbnk.uk
AUTHENTIK_HOST_BROWSER=https://authentik.rbnk.uk

# Database Configuration (using shared Supabase PostgreSQL)
PG_USER=authentik
PG_DB=authentik
PG_PASS=your-database-password

# Outpost Token (generated in Authentik UI)
AUTHENTIK_OUTPOST_TOKEN=your-outpost-token-here

Critical OAuth Flow Fix

The AUTHENTIK_HOST_BROWSER environment variable is essential for proper OAuth flow operation:

  • Problem: OAuth redirects were failing when internal container names were used
  • Solution: Set AUTHENTIK_HOST_BROWSER to the public HTTPS URL
  • Impact: Ensures OAuth callbacks use the correct public domain for browser-based flows

The proxy outpost is deployed on a separate subdomain (auth-proxy.rbnk.uk) to ensure proper cookie domain handling:

  • Main Service: authentik.rbnk.uk - User interface and administration
  • Proxy Outpost: auth-proxy.rbnk.uk - Forward authentication endpoint
  • Cookie Domain: .rbnk.uk - Allows cookies to work across all subdomains

Protected Services

The following services are protected by Authentik authentication (Priority 1 router configuration):

Infrastructure Services

  • Prometheus (prometheus.rbnk.uk) - Monitoring metrics and web UI
  • Portainer (portainer.rbnk.uk) - Docker management interface
  • Rclone (rclone.rbnk.uk) - Cloud storage backup interface
  • Glance (glance.rbnk.uk) - Infrastructure dashboard

Application Services

  • LiteLLM (llm.rbnk.uk) - AI proxy web interface
  • Apprise (apprise.rbnk.uk) - Notification service web UI
  • Paperless-AI (paperless-ai.rbnk.uk) - Document management
  • Metube (metube.rbnk.uk) - YouTube downloader interface

API Access Patterns

Each protected service maintains API access through higher-priority routes that bypass Authentik:

LiteLLM API Access

# API routes (no authentication)
PathPrefix(/v1/) || PathPrefix(/chat/) || PathPrefix(/completions) || PathPrefix(/models) || PathPrefix(/health)
Priority: 100

Prometheus API Access

# Metrics and API routes (no authentication)
PathPrefix(/api/) || PathPrefix(/metrics)
Priority: 100

Apprise API Access

# Notification API routes (no authentication)
PathPrefix(/notify/) || PathPrefix(/json/) || PathPrefix(/get/) || PathPrefix(/add/) || PathPrefix(/del/) || PathPrefix(/form/)
Priority: 100

Traefik Integration

Middleware Configuration

Authentik integrates with Traefik through custom middleware defined in /srv/dockerdata/traefik/dynamic/authentik.yml:

http:
  middlewares:
    authentik:
      forwardAuth:
        address: http://authentik-proxy-1:9000/outpost.goauthentik.io/auth/traefik
        trustForwardHeader: true
        authResponseHeaders:
          - X-authentik-username
          - X-authentik-groups
          - X-authentik-email
          - X-authentik-name
          - X-authentik-uid
          - X-authentik-jwt

    authentik-secured:
      chain:
        middlewares:
          - redirect-to-https
          - authentik

Service Label Examples

Browser + API Service (Dual Route)

labels:
  # Browser access (protected)
  - "traefik.http.routers.service.middlewares=authentik-secured@file"
  # API access (unprotected, higher priority)
  - "traefik.http.routers.service-api.rule=Host(`service.rbnk.uk`) && PathPrefix(`/api/`)"
  - "traefik.http.routers.service-api.priority=100"
  - "traefik.http.routers.service-api.middlewares=api-access@file"

Browser-Only Service

labels:
  - "traefik.http.routers.service.middlewares=authentik-secured@file"

User Management

Default Admin User

After initial setup, access Authentik at https://authentik.rbnk.uk and create the initial admin user through the web interface.

User Authentication Flow

  1. User accesses protected service (e.g., https://prometheus.rbnk.uk)
  2. Traefik forwards request to Authentik proxy outpost
  3. If not authenticated, user is redirected to Authentik login page
  4. After successful authentication, user is redirected back to original service
  5. Authentik sets authentication cookies for .rbnk.uk domain
  6. Subsequent requests include authentication headers for the service

Session Management

  • Session Storage: Redis-based session storage in Authentik stack
  • Cookie Domain: .rbnk.uk - works across all subdomains
  • Session Duration: Configurable in Authentik policies (default: 24 hours)
  • Logout: Available from any protected service or Authentik interface

Outpost Configuration

Creating the Outpost Token

  1. Access Authentik admin interface at https://authentik.rbnk.uk
  2. Navigate to ApplicationsOutposts
  3. Create new outpost with type "Proxy"
  4. Generate token and add to AUTHENTIK_OUTPOST_TOKEN in .env
  5. Restart the proxy container to apply the token

Outpost Providers

Create providers for each service in the Authentik interface:

  1. ApplicationsProvidersCreate Proxy Provider
  2. Configure external host (e.g., https://prometheus.rbnk.uk)
  3. Set authorization flow (default: implicit consent)
  4. Assign to appropriate application

OAuth2/OIDC Provider Configuration

Authentik can act as an OAuth2/OpenID Connect provider for external applications, allowing them to use Authentik for authentication.

Creating an OIDC Provider

  1. Navigate to Providers:
  2. Go to ApplicationsProviders in the left menu
  3. Click CreateOAuth2/OpenID Provider

  4. Configure the Provider:

  5. Name: Choose a descriptive name (e.g., "My App OIDC")
  6. Authorization flow: Select based on your needs:
    • default-provider-authorization-implicit-consent - No user consent screen
    • default-provider-authorization-explicit-consent - Shows consent screen
  7. Client type:
    • Confidential: For server-side applications (provides client secret)
    • Public: For SPAs, mobile apps, or CLIs (no client secret)
  8. Client ID: Auto-generated or set custom (e.g., my-app-client)
  9. Client Secret: Auto-generated for confidential clients
  10. Redirect URIs: Add all valid callback URLs:
    https://myapp.example.com/auth/callback
    https://myapp.example.com/oauth2/callback
    http://localhost:3000/auth/callback (for development)
    
  11. Scopes: Select required scopes:

    • openid - Required for OIDC
    • email - User email access
    • profile - User profile information
    • offline_access - Refresh tokens
  12. Advanced Settings (optional):

  13. Access code validity: How long authorization codes are valid
  14. Access token validity: Token lifetime (default: hours=1)
  15. Refresh token validity: For offline access (default: days=30)
  16. Include claims in id_token: Enable for user info in ID token

Creating an Application

  1. Navigate to Applications:
  2. Go to ApplicationsApplications
  3. Click Create

  4. Configure the Application:

  5. Name: User-friendly name shown on consent screen
  6. Slug: URL-safe identifier
  7. Provider: Select the OIDC provider created above
  8. Policy engine mode: Any (default) or All (stricter)
  9. UI settings: Logo, description, publisher

  10. Assign Policies (optional):

  11. User/group restrictions
  12. Network/IP restrictions
  13. Time-based access

Finding OIDC Credentials

After creating the provider and application:

  1. Get Credentials:
  2. Go to ApplicationsProviders
  3. Click on your OAuth2/OpenID provider
  4. View credentials:

    • Client ID: Displayed in provider details
    • Client Secret: Click "Show" button (confidential clients only)
    • Issuer: https://authentik.rbnk.uk/application/o/<provider-slug>/
  5. OIDC Discovery URL:

    https://authentik.rbnk.uk/application/o/<provider-slug>/.well-known/openid-configuration
    

OIDC Endpoints

Your application will use these endpoints:

  • Authorization: https://authentik.rbnk.uk/application/o/authorize/
  • Token: https://authentik.rbnk.uk/application/o/token/
  • UserInfo: https://authentik.rbnk.uk/application/o/userinfo/
  • JWKS: https://authentik.rbnk.uk/application/o/<provider-slug>/jwks/
  • Logout: https://authentik.rbnk.uk/application/o/<provider-slug>/end-session/

Integration Examples

Node.js with Passport

const passport = require('passport');
const { Strategy } = require('openid-client');

// Discover OIDC configuration
const issuer = await Issuer.discover('https://authentik.rbnk.uk/application/o/<provider-slug>/');
const client = new issuer.Client({
  client_id: 'your-client-id',
  client_secret: 'your-client-secret',
  redirect_uris: ['https://myapp.com/auth/callback'],
  response_types: ['code'],
});

passport.use('oidc', new Strategy({ client }, (tokenSet, userinfo, done) => {
  return done(null, userinfo);
}));

Python with Authlib

from authlib.integrations.flask_client import OAuth

oauth = OAuth(app)
oauth.register(
    name='authentik',
    client_id='your-client-id',
    client_secret='your-client-secret',
    server_metadata_url='https://authentik.rbnk.uk/application/o/<provider-slug>/.well-known/openid-configuration',
    client_kwargs={'scope': 'openid email profile'}
)

Manual Token Validation

# Get access token
TOKEN_RESPONSE=$(curl -X POST https://authentik.rbnk.uk/application/o/token/ \
  -d "grant_type=authorization_code" \
  -d "code=AUTHORIZATION_CODE" \
  -d "redirect_uri=https://myapp.com/callback" \
  -d "client_id=your-client-id" \
  -d "client_secret=your-client-secret")

# Extract access token
ACCESS_TOKEN=$(echo $TOKEN_RESPONSE | jq -r '.access_token')

# Get user info
curl -H "Authorization: Bearer $ACCESS_TOKEN" \
  https://authentik.rbnk.uk/application/o/userinfo/

Testing OIDC Configuration

  1. Verify Discovery Endpoint:

    curl https://authentik.rbnk.uk/application/o/<provider-slug>/.well-known/openid-configuration | jq
    

  2. Test Authorization Flow:

  3. Open in browser: https://authentik.rbnk.uk/application/o/authorize/?client_id=<client-id>&redirect_uri=<callback>&response_type=code&scope=openid%20email%20profile
  4. Should redirect to login if not authenticated
  5. After login, redirects to callback with authorization code

  6. Validate Tokens:

  7. ID tokens are JWTs - decode at jwt.io
  8. Verify signature with JWKS endpoint
  9. Check claims match expected values

Common OIDC Use Cases

  1. Single Sign-On (SSO) for internal applications
  2. API Authentication with bearer tokens
  3. Mobile App Authentication with PKCE flow
  4. Third-party Integrations requiring OAuth2
  5. Microservices Authentication with service accounts

Security Best Practices

  1. Always use HTTPS for redirect URIs
  2. Validate redirect URIs strictly
  3. Use PKCE for public clients
  4. Rotate client secrets regularly
  5. Limit token lifetimes appropriately
  6. Enable consent for sensitive applications

Monitoring and Troubleshooting

Service Status

# Check all Authentik services
docker compose -f authentik/docker-compose.yml ps

# View server logs
docker compose -f authentik/docker-compose.yml logs -f server

# View proxy outpost logs
docker compose -f authentik/docker-compose.yml logs -f proxy

# View worker logs
docker compose -f authentik/docker-compose.yml logs -f worker

Common Issues

OAuth Flow Failures

  • Symptom: Redirect loops or "invalid redirect URI" errors
  • Solution: Verify AUTHENTIK_HOST_BROWSER is set to public HTTPS URL
  • Check: Ensure outpost token is properly configured
  • Symptom: Authentication doesn't persist across services
  • Solution: Verify proxy outpost is on separate subdomain (auth-proxy.rbnk.uk)
  • Check: Confirm cookie domain is set to .rbnk.uk

Database Connection Errors

  • Symptom: Server fails to start with PostgreSQL errors
  • Solution: Verify database credentials and network connectivity
  • Check: Ensure supa-db is running and accessible

Health Checks

# Test Authentik server health
curl -I https://authentik.rbnk.uk

# Test proxy outpost health
curl -I https://auth-proxy.rbnk.uk

# Test forward auth endpoint
curl -I http://authentik-proxy-1:9000/outpost.goauthentik.io/auth/traefik

Security Considerations

Token Management

  • Outpost tokens should be rotated regularly
  • Store tokens securely in .env files with proper permissions (640)
  • Monitor token usage in Authentik logs

Network Security

  • Proxy outpost communicates internally with server via Docker network
  • External access only through Traefik with proper TLS termination
  • Database access restricted to internal network

Authentication Policies

  • Configure appropriate session timeouts
  • Implement MFA for administrative users
  • Review and audit user access regularly

Backup and Recovery

Configuration Backup

# Backup Authentik configuration
docker exec authentik-server-1 ak export > authentik-config-backup.json

# Backup custom templates and media
tar -czf authentik-data-backup.tar.gz authentik/media/ authentik/custom-templates/

Database Backup

Authentik data is stored in the shared PostgreSQL instance and is included in the regular Supabase backup process.

Recovery Process

  1. Restore database from Supabase backup
  2. Restore media and template files
  3. Import configuration: docker exec authentik-server-1 ak import < authentik-config-backup.json
  4. Recreate outpost tokens and update .env files

Performance Tuning

Redis Optimization

  • Authentik uses dedicated Redis instance for session storage
  • Monitor Redis memory usage and configure appropriate limits
  • Enable Redis persistence for session recovery

Database Performance

  • Monitor PostgreSQL connections and query performance
  • Consider connection pooling for high-traffic deployments
  • Regular database maintenance through Supabase procedures

Proxy Outpost Scaling

  • Single proxy outpost handles all authentication requests
  • Monitor response times and consider horizontal scaling if needed
  • Load balancing multiple outposts through Traefik if required

Integration Examples

Adding New Protected Service

  1. Configure Service Labels:

    labels:
      - "traefik.http.routers.newservice.middlewares=authentik-secured@file"
      # Add API route if needed
      - "traefik.http.routers.newservice-api.rule=Host(`newservice.rbnk.uk`) && PathPrefix(`/api/`)"
      - "traefik.http.routers.newservice-api.priority=100"
      - "traefik.http.routers.newservice-api.middlewares=api-access@file"
    

  2. Create Provider in Authentik:

  3. External host: https://newservice.rbnk.uk
  4. Authorization flow: Default
  5. Skip path regex: /api/.* (if API access needed)

  6. Create Application:

  7. Link to the provider
  8. Set appropriate policies and user access

Custom Authentication Headers

Services can access user information through headers provided by Authentik:

X-authentik-username: [email protected]
X-authentik-groups: admin,users
X-authentik-email: [email protected]
X-authentik-name: John Doe
X-authentik-uid: user-uuid

Applications can use these headers for user context and authorization decisions.

Future Enhancements

Planned Improvements

  • Multi-factor authentication (MFA) implementation
  • LDAP/Active Directory integration
  • Advanced policy configurations
  • Single sign-out (SLO) implementation
  • API key authentication for service-to-service communication

Scalability Considerations

  • Horizontal scaling of proxy outposts
  • Database connection pooling
  • Redis cluster for session storage
  • Load balancing and failover strategies