Skip to content

Deploying Authentik

Introduction

Authentik is a modern, powerful, open-source identity provider (IdP) focused on flexibility and versatility. It provides comprehensive authentication, authorization, and user management capabilities, supporting a wide range of protocols including OAuth2, SAML, LDAP, and SCIM. Built with Python and Django, Authentik offers a sleek, intuitive interface for managing users, groups, applications, and policies.

Authentik stands out for its:

  • Multi-Protocol Support: Native support for OAuth2, OpenID Connect, SAML, LDAP, and SCIM
  • Policy Engine: Powerful, flexible policy system for fine-grained access control
  • Modern UI: Clean, responsive interface for both administrators and end-users
  • Self-Service Portal: User-friendly portal for password resets, profile management, and app access
  • Flow-Based Architecture: Customizable authentication and authorization flows
  • Enterprise-Ready: Support for MFA, SSO, user provisioning, and audit logging
  • API-First Design: Comprehensive REST API for automation and integrations
  • Active Development: Regular updates with new features and security improvements

This comprehensive guide walks you through deploying Authentik on Klutch.sh using Docker, including detailed installation steps, database configuration, persistent storage setup, sample Dockerfiles, environment variables, and production-ready best practices.

Prerequisites

Before you begin, ensure you have the following:

  • A Klutch.sh account
  • A GitHub account with a repository for your Authentik project
  • Docker installed locally for testing (optional but recommended)
  • A PostgreSQL database (can be deployed separately on Klutch.sh or use an external provider)
  • A Redis instance (can be deployed separately on Klutch.sh or use an external provider)
  • Basic understanding of Docker, identity providers, and authentication concepts

Installation and Setup

Step 1: Create Your Project Directory

First, create a new directory for your Authentik deployment project:

Terminal window
mkdir authentik-klutch
cd authentik-klutch
git init

Step 2: Create the Dockerfile

Create a Dockerfile in your project root directory. This will define your Authentik container configuration:

FROM ghcr.io/goauthentik/server:latest
# Set working directory
WORKDIR /
# Expose the default Authentik ports
# 9000 for web server
# 9443 for HTTPS (optional)
EXPOSE 9000 9443
# Health check
HEALTHCHECK --interval=30s --timeout=10s --start-period=60s --retries=3 \
CMD wget --no-verbose --tries=1 --spider http://localhost:9000/-/health/ready/ || exit 1
# Default command (provided by base image)
CMD ["server"]

Note: This Dockerfile uses the official Authentik server image. The base image is maintained by the Authentik team and includes all necessary components for running the web server and worker processes.

Step 3: Advanced Dockerfile with Custom Configuration

For a production-ready setup with additional customization options:

FROM ghcr.io/goauthentik/server:2024.8.3
# Install additional tools if needed
USER root
RUN apt-get update && \
apt-get install -y --no-install-recommends \
ca-certificates \
curl \
&& rm -rf /var/lib/apt/lists/*
# Switch back to authentik user
USER authentik
# Set working directory
WORKDIR /
# Expose ports
EXPOSE 9000 9443
# Health check for readiness
HEALTHCHECK --interval=30s --timeout=10s --start-period=90s --retries=3 \
CMD curl -f http://localhost:9000/-/health/ready/ || exit 1
# Use the default command from base image
CMD ["server"]

Important Notes:

  • Pin to a specific version (e.g., 2024.8.3) for reproducible deployments
  • Authentik requires both a PostgreSQL database and Redis for operation
  • The container runs as the authentik user for security
  • Port 9000 is the primary HTTP port for the web interface

Step 4: Create Worker Dockerfile (Optional)

For production setups, you may want to run separate worker containers. Create a Dockerfile.worker:

FROM ghcr.io/goauthentik/server:2024.8.3
# Switch to authentik user
USER authentik
# Set working directory
WORKDIR /
# Health check
HEALTHCHECK --interval=30s --timeout=10s --start-period=60s --retries=3 \
CMD ak healthcheck || exit 1
# Worker command
CMD ["worker"]

Step 5: Create Environment Configuration

Create a .env.example file to document the required environment variables:

Terminal window
# PostgreSQL Configuration (Required)
AUTHENTIK_POSTGRESQL__HOST=postgres-app.klutch.sh
AUTHENTIK_POSTGRESQL__PORT=8000
AUTHENTIK_POSTGRESQL__NAME=authentik
AUTHENTIK_POSTGRESQL__USER=authentik
AUTHENTIK_POSTGRESQL__PASSWORD=your-secure-postgres-password
# Redis Configuration (Required)
AUTHENTIK_REDIS__HOST=redis-app.klutch.sh
AUTHENTIK_REDIS__PORT=8000
AUTHENTIK_REDIS__DB=0
# Secret Key (Required - Generate with: openssl rand -base64 60)
AUTHENTIK_SECRET_KEY=your-secret-key-here-replace-with-random-string
# Error Reporting
AUTHENTIK_ERROR_REPORTING__ENABLED=false
# Email Configuration (Optional but recommended)
AUTHENTIK_EMAIL__HOST=smtp.example.com
AUTHENTIK_EMAIL__PORT=587
AUTHENTIK_EMAIL__USERNAME=authentik@example.com
AUTHENTIK_EMAIL__PASSWORD=email-password
AUTHENTIK_EMAIL__USE_TLS=true
AUTHENTIK_EMAIL__FROM=authentik@example.com
# Bootstrap Configuration (Optional)
AUTHENTIK_BOOTSTRAP_PASSWORD=initial-admin-password
AUTHENTIK_BOOTSTRAP_TOKEN=bootstrap-token-for-automation
# Disable built-in database (we use external PostgreSQL)
AUTHENTIK_POSTGRESQL__USE_PGBOUNCER=false

Security Notes:

  • Never commit actual passwords or secrets to your repository
  • Use a strong, randomly generated AUTHENTIK_SECRET_KEY
  • Change the bootstrap password immediately after first login
  • Store all sensitive credentials as environment variables in Klutch.sh dashboard

Step 6: Generate Secret Key

Generate a secure secret key for Authentik:

Terminal window
openssl rand -base64 60

Copy the output and use it for AUTHENTIK_SECRET_KEY in your environment variables.

Step 7: Create README Documentation

Create a README.md file with deployment instructions:

# Authentik Identity Provider Deployment
This repository contains the Docker configuration for deploying Authentik on Klutch.sh.
## Quick Start
1. Deploy PostgreSQL and Redis instances on Klutch.sh
2. Update environment variables in Klutch.sh dashboard
3. Deploy this repository
4. Access Authentik at your assigned URL
5. Log in with bootstrap credentials
## Initial Setup
After deployment:
1. Log in using `AUTHENTIK_BOOTSTRAP_PASSWORD`
2. Change the admin password immediately
3. Configure your first application
4. Set up authentication flows
5. Configure email for notifications
## Environment Variables
See `.env.example` for required configuration.
## Documentation
- <a href="https://docs.goauthentik.io/" target="_blank" rel="noopener noreferrer">Authentik Documentation</a>
- <a href="https://docs.klutch.sh/?utm_source=docs" target="_blank">Klutch.sh Docs</a>

Step 8: Test Locally with Docker Compose (Optional)

For local testing, you can use Docker Compose. Create a docker-compose.yml:

version: "3.8"
services:
postgresql:
image: postgres:16-alpine
restart: unless-stopped
environment:
POSTGRES_PASSWORD: authentik-password
POSTGRES_USER: authentik
POSTGRES_DB: authentik
volumes:
- postgres-data:/var/lib/postgresql/data
healthcheck:
test: ["CMD-SHELL", "pg_isready -U authentik"]
interval: 10s
timeout: 5s
retries: 5
redis:
image: redis:7-alpine
restart: unless-stopped
command: --save 60 1 --loglevel warning
volumes:
- redis-data:/data
healthcheck:
test: ["CMD", "redis-cli", "ping"]
interval: 10s
timeout: 5s
retries: 5
authentik:
build: .
restart: unless-stopped
command: server
environment:
AUTHENTIK_POSTGRESQL__HOST: postgresql
AUTHENTIK_POSTGRESQL__PORT: 5432
AUTHENTIK_POSTGRESQL__NAME: authentik
AUTHENTIK_POSTGRESQL__USER: authentik
AUTHENTIK_POSTGRESQL__PASSWORD: authentik-password
AUTHENTIK_REDIS__HOST: redis
AUTHENTIK_REDIS__PORT: 6379
AUTHENTIK_SECRET_KEY: change-me-in-production
AUTHENTIK_ERROR_REPORTING__ENABLED: "false"
AUTHENTIK_BOOTSTRAP_PASSWORD: changeme123
ports:
- "9000:9000"
depends_on:
postgresql:
condition: service_healthy
redis:
condition: service_healthy
volumes:
- authentik-media:/media
- authentik-templates:/templates
worker:
build: .
restart: unless-stopped
command: worker
environment:
AUTHENTIK_POSTGRESQL__HOST: postgresql
AUTHENTIK_POSTGRESQL__PORT: 5432
AUTHENTIK_POSTGRESQL__NAME: authentik
AUTHENTIK_POSTGRESQL__USER: authentik
AUTHENTIK_POSTGRESQL__PASSWORD: authentik-password
AUTHENTIK_REDIS__HOST: redis
AUTHENTIK_REDIS__PORT: 6379
AUTHENTIK_SECRET_KEY: change-me-in-production
AUTHENTIK_ERROR_REPORTING__ENABLED: "false"
depends_on:
postgresql:
condition: service_healthy
redis:
condition: service_healthy
volumes:
- authentik-media:/media
- authentik-templates:/templates
volumes:
postgres-data:
redis-data:
authentik-media:
authentik-templates:

Test locally:

Terminal window
# Build and start all services
docker-compose up -d
# View logs
docker-compose logs -f authentik
# Access Authentik at http://localhost:9000
# Stop and remove when done
docker-compose down

Note: Docker Compose is only for local development and testing. Klutch.sh does not support Docker Compose for deployments.

Step 9: Push to GitHub

Commit your Dockerfile and configuration files to your GitHub repository:

Terminal window
git add Dockerfile .env.example README.md
git commit -m "Add Authentik Dockerfile and configuration"
git remote add origin https://github.com/yourusername/authentik-klutch.git
git push -u origin main

Deploying to Klutch.sh

Now that your Authentik project is ready and pushed to GitHub, follow these steps to deploy it on Klutch.sh with persistent storage.

Prerequisites: Deploy PostgreSQL and Redis

Before deploying Authentik, you need to set up PostgreSQL and Redis instances:

  1. Deploy PostgreSQL: Follow the PostgreSQL deployment guide to create a PostgreSQL instance on Klutch.sh
  2. Deploy Redis: Follow the Redis deployment guide to create a Redis instance on Klutch.sh

Note the connection details for both services, as you’ll need them for Authentik’s environment variables.

Deployment Steps

    1. Log in to Klutch.sh

      Navigate to klutch.sh/app and sign in to your account.

    2. Create a New Project

      Go to Create Project and give your project a meaningful name (e.g., “Authentik Identity Provider”).

    3. Create a New App

      Navigate to Create App and configure the following settings:

    4. Select Your Repository

      • Choose GitHub as your Git source
      • Select the repository containing your Authentik Dockerfile
      • Choose the branch you want to deploy (usually main or master)
    5. Configure Traffic Type

      • Traffic Type: Select HTTP (Authentik serves a web interface via HTTP)
      • Internal Port: Set to 9000 (the default port that Authentik listens on)
    6. Set Environment Variables

      Add the following environment variables for your Authentik configuration. Replace the placeholder values with your actual database and Redis connection details:

      Required Variables:

      • AUTHENTIK_POSTGRESQL__HOST: Your PostgreSQL hostname (e.g., postgres-app.klutch.sh)
      • AUTHENTIK_POSTGRESQL__PORT: Set to 8000 (Klutch.sh’s TCP port for databases)
      • AUTHENTIK_POSTGRESQL__NAME: Database name (e.g., authentik)
      • AUTHENTIK_POSTGRESQL__USER: Database username (e.g., authentik)
      • AUTHENTIK_POSTGRESQL__PASSWORD: Your secure PostgreSQL password
      • AUTHENTIK_REDIS__HOST: Your Redis hostname (e.g., redis-app.klutch.sh)
      • AUTHENTIK_REDIS__PORT: Set to 8000 (Klutch.sh’s TCP port for databases)
      • AUTHENTIK_REDIS__DB: Redis database number (default: 0)
      • AUTHENTIK_SECRET_KEY: Your randomly generated secret key (use openssl rand -base64 60)
      • AUTHENTIK_ERROR_REPORTING__ENABLED: Set to false to disable anonymous error reporting

      Bootstrap Variables (Recommended for initial setup):

      • AUTHENTIK_BOOTSTRAP_PASSWORD: Initial admin password (change this after first login)
      • AUTHENTIK_BOOTSTRAP_EMAIL: Admin email address (e.g., admin@example.com)

      Email Configuration (Recommended for production):

      • AUTHENTIK_EMAIL__HOST: SMTP server hostname (e.g., smtp.gmail.com)
      • AUTHENTIK_EMAIL__PORT: SMTP port (usually 587 for TLS or 465 for SSL)
      • AUTHENTIK_EMAIL__USERNAME: SMTP username
      • AUTHENTIK_EMAIL__PASSWORD: SMTP password
      • AUTHENTIK_EMAIL__USE_TLS: Set to true to enable TLS
      • AUTHENTIK_EMAIL__FROM: Sender email address (e.g., noreply@example.com)

      Security Note: Always use strong, unique passwords and mark sensitive variables as secrets in the Klutch.sh dashboard.

    7. Attach Persistent Volumes

      Authentik requires persistent storage for media files (logos, icons) and custom templates. Add two volumes:

      Media Volume:

      • Click “Add Volume” in the Volumes section
      • Mount Path: Enter /media
      • Size: Choose 5-10GB (stores uploaded logos, icons, and user avatars)

      Templates Volume:

      • Click “Add Volume” again
      • Mount Path: Enter /templates
      • Size: Choose 1-2GB (stores custom email and page templates)

      Important: Persistent storage ensures your customizations and uploaded assets persist across deployments and restarts.

    8. Configure Additional Settings

      • Region: Select the region closest to your users for optimal latency
      • Compute Resources: Choose CPU and memory based on your user count:
        • Small (< 100 users): 512MB RAM, 0.5 CPU
        • Medium (100-1000 users): 1GB RAM, 1 CPU
        • Large (1000+ users): 2GB+ RAM, 2+ CPU
      • Instances: Start with 1 instance (you can scale horizontally later)
    9. Deploy Your Application

      Click “Create” to start the deployment. Klutch.sh will:

      • Automatically detect your Dockerfile in the repository root
      • Build the Docker image with Authentik
      • Attach the persistent volumes
      • Configure environment variables
      • Start your Authentik container
      • Assign a URL for external access
    10. Access Your Authentik Dashboard

      Once deployment is complete, you’ll receive a URL like example-app.klutch.sh. Navigate to this URL in your browser to access your Authentik instance:

      https://example-app.klutch.sh/if/flow/initial-setup/

      Log in using the bootstrap credentials you configured:

      • Username: akadmin (default admin username)
      • Password: The value you set in AUTHENTIK_BOOTSTRAP_PASSWORD

      Important: Change the admin password immediately after first login for security.


Post-Deployment Configuration

After your Authentik instance is deployed, complete the initial setup:

Initial Admin Setup

  1. Change Admin Password

    • Navigate to Admin InterfaceDirectoryUsers
    • Select the akadmin user
    • Change the password to a strong, unique password
    • Update the email address
  2. Create Regular Admin User

    • Create a new user with administrative privileges
    • Assign to the authentik Admins group
    • Use this for daily administration tasks
  3. Disable Bootstrap User (Optional)

    • Once you have a working admin account, you can disable the akadmin bootstrap user for security

Configure Your First Application

  1. Navigate to Applications

    • Go to Admin InterfaceApplicationsApplications
    • Click Create
  2. Configure Application Settings

    • Name: Your application name (e.g., “MyApp”)
    • Slug: URL-friendly identifier (e.g., myapp)
    • Provider: Create a new provider (OAuth2, SAML, LDAP, etc.)
  3. Create Provider

    For OAuth2/OpenID Connect:

    • Name: Provider name
    • Authorization Flow: Default authorization flow
    • Client Type: Confidential (for server-side apps) or Public (for SPAs)
    • Redirect URIs: Your application’s callback URLs

    Copy the Client ID and Client Secret for use in your application.

Set Up Authentication Flows

Authentik’s power comes from its flexible flow system:

  1. Review Default Flows

    • Navigate to Admin InterfaceFlows & StagesFlows
    • Review the default authentication, authorization, and enrollment flows
  2. Customize Flows (Optional)

    • Create custom flows for specific use cases
    • Add stages like MFA, password policies, or user agreement
    • Bind flows to applications

Configure Email Notifications

Set up email for password resets, notifications, and alerts:

  1. Test Email Configuration

    • Navigate to Admin InterfaceSystemSystem Tasks
    • Find the “Test E-Mail” task
    • Click Run to send a test email
  2. Customize Email Templates

    • Navigate to Admin InterfaceCustomizationEmail Templates
    • Customize templates for password resets, invitations, and notifications

Environment Variables Reference

Complete list of Authentik environment variables you can configure in Klutch.sh:

Database Configuration

VariableDescriptionRequiredDefault
AUTHENTIK_POSTGRESQL__HOSTPostgreSQL hostnameYesNone
AUTHENTIK_POSTGRESQL__PORTPostgreSQL portYes5432
AUTHENTIK_POSTGRESQL__NAMEDatabase nameYesauthentik
AUTHENTIK_POSTGRESQL__USERDatabase usernameYesauthentik
AUTHENTIK_POSTGRESQL__PASSWORDDatabase passwordYesNone
AUTHENTIK_POSTGRESQL__USE_PGBOUNCERUse PgBouncerNofalse
AUTHENTIK_POSTGRESQL__USE_PGPOOLUse PgPoolNofalse

Redis Configuration

VariableDescriptionRequiredDefault
AUTHENTIK_REDIS__HOSTRedis hostnameYesNone
AUTHENTIK_REDIS__PORTRedis portYes6379
AUTHENTIK_REDIS__DBRedis database numberNo0
AUTHENTIK_REDIS__PASSWORDRedis passwordNoNone
AUTHENTIK_REDIS__TLSUse TLS for RedisNofalse

Core Configuration

VariableDescriptionRequiredDefault
AUTHENTIK_SECRET_KEYSecret key for signingYesNone
AUTHENTIK_ERROR_REPORTING__ENABLEDEnable error reportingNotrue
AUTHENTIK_LOG_LEVELLogging levelNoinfo
AUTHENTIK_COOKIE_DOMAINCookie domainNoAuto-detected
AUTHENTIK_DISABLE_STARTUP_ANALYTICSDisable startup analyticsNofalse

Email Configuration

VariableDescriptionRequiredDefault
AUTHENTIK_EMAIL__HOSTSMTP server hostnameNolocalhost
AUTHENTIK_EMAIL__PORTSMTP portNo25
AUTHENTIK_EMAIL__USERNAMESMTP usernameNoNone
AUTHENTIK_EMAIL__PASSWORDSMTP passwordNoNone
AUTHENTIK_EMAIL__USE_TLSUse TLSNofalse
AUTHENTIK_EMAIL__USE_SSLUse SSLNofalse
AUTHENTIK_EMAIL__TIMEOUTConnection timeoutNo10
AUTHENTIK_EMAIL__FROMSender email addressNoNone

Bootstrap Configuration

VariableDescriptionRequiredDefault
AUTHENTIK_BOOTSTRAP_PASSWORDInitial admin passwordNoNone
AUTHENTIK_BOOTSTRAP_TOKENBootstrap API tokenNoNone
AUTHENTIK_BOOTSTRAP_EMAILAdmin emailNoNone

Advanced Configuration

VariableDescriptionRequiredDefault
AUTHENTIK_LISTEN__HTTPHTTP listen addressNo0.0.0.0:9000
AUTHENTIK_LISTEN__HTTPSHTTPS listen addressNo0.0.0.0:9443
AUTHENTIK_WEB__WORKERSNumber of web workersNo2
AUTHENTIK_OUTPOSTS__DISCOVEREnable outpost discoveryNotrue

Configuring Single Sign-On (SSO)

Authentik excels at providing SSO for your applications. Here’s how to set it up:

OAuth2/OpenID Connect Provider

Most modern applications support OAuth2 or OpenID Connect:

  1. Create Provider

    • Navigate to Admin InterfaceApplicationsProviders
    • Click CreateOAuth2/OpenID Provider
  2. Configure Provider

    Name: MyApp OAuth Provider
    Authorization Flow: default-provider-authorization-explicit-consent
    Client Type: Confidential
    Client ID: (auto-generated)
    Client Secret: (auto-generated)
    Redirect URIs: https://myapp.com/auth/callback
    Signing Key: (select or create)
  3. Configure Application

    • Link the provider to your application
    • Copy Client ID and Secret for your app configuration
  4. Configure Your Application

    In your application, configure OAuth2 with:

    • Authorization URL: https://example-app.klutch.sh/application/o/authorize/
    • Token URL: https://example-app.klutch.sh/application/o/token/
    • User Info URL: https://example-app.klutch.sh/application/o/userinfo/
    • Client ID: From Authentik
    • Client Secret: From Authentik
    • Scopes: openid profile email

SAML Provider

For applications that require SAML:

  1. Create SAML Provider

    • Navigate to Admin InterfaceApplicationsProviders
    • Click CreateSAML Provider
  2. Configure SAML Settings

    Name: MyApp SAML Provider
    Authorization Flow: default-provider-authorization-explicit-consent
    ACS URL: https://myapp.com/saml/acs
    Issuer: https://example-app.klutch.sh
    Service Provider Binding: Post
    Audience: https://myapp.com
  3. Download Metadata

    • Download the SAML metadata XML
    • Upload to your application’s SAML configuration

LDAP Provider (Outpost)

For applications requiring LDAP authentication:

  1. Create LDAP Outpost

    • Navigate to Admin InterfaceApplicationsOutposts
    • Click Create
    • Select LDAP type
  2. Configure LDAP Settings

    Name: LDAP Outpost
    Type: LDAP
    Base DN: dc=ldap,dc=goauthentik,dc=io
    TLS Server Name: ldap.example.com
  3. Configure Your Application

    • LDAP Server: Your outpost hostname
    • Port: 389 (LDAP) or 636 (LDAPS)
    • Base DN: From outpost configuration
    • Bind DN: User DN in Authentik
    • Bind Password: User password

Customization

Branding and Theming

Customize Authentik’s appearance to match your organization:

  1. Upload Logo

    • Navigate to Admin InterfaceCustomizationBrands
    • Edit the default brand
    • Upload your logo and favicon
  2. Customize Colors

    • Add custom CSS in the brand settings
    • Override default colors and styling
  3. Custom Footer Links

    • Add privacy policy, terms of service, and support links
    • Configure in brand settings

Custom Flows and Stages

Create custom authentication experiences:

  1. Create Custom Stage

    • Navigate to Admin InterfaceFlows & StagesStages
    • Choose stage type (Password, MFA, Consent, etc.)
    • Configure stage settings
  2. Create Custom Flow

    • Navigate to Admin InterfaceFlows & StagesFlows
    • Click Create
    • Add stages to your flow
    • Configure stage bindings
  3. Assign Flow to Application

    • Edit your application
    • Select your custom flow
    • Save changes

Multi-Factor Authentication (MFA)

Enable MFA for enhanced security:

Configuring TOTP (Time-Based One-Time Password)

  1. Create TOTP Stage

    • Navigate to Admin InterfaceFlows & StagesStages
    • Click CreateAuthenticator Validation Stage
    • Select TOTP device classes
  2. Add to Authentication Flow

    • Edit your authentication flow
    • Add the TOTP stage after password validation
    • Configure as required or optional
  3. User Enrollment

    • Users can enroll TOTP devices via the user interface
    • Navigate to User InterfaceSettingsMFA Devices
    • Scan QR code with authenticator app

Configuring WebAuthn (Security Keys)

  1. Create WebAuthn Stage

    • Create an Authenticator Validation Stage
    • Select WebAuthn device classes
  2. Configure WebAuthn Settings

    • Set authenticator attachment (platform, cross-platform, or both)
    • Configure user verification requirements
  3. User Enrollment

    • Users can register security keys or biometric devices
    • Navigate to User InterfaceSettingsMFA Devices
    • Follow the browser prompts to register device

User Management

Creating Users

  1. Manual User Creation

    • Navigate to Admin InterfaceDirectoryUsers
    • Click Create
    • Fill in user details
    • Assign to groups
  2. Self-Service Enrollment

    • Configure enrollment flow
    • Share enrollment link with users
    • Users create their own accounts
  3. Bulk User Import

    • Use the Authentik API
    • Import users from CSV or external sources
    • Automate with scripts

Managing Groups

  1. Create Groups

    • Navigate to Admin InterfaceDirectoryGroups
    • Click Create
    • Set group name and parent group
  2. Assign Users to Groups

    • Edit group
    • Add users
    • Configure group permissions
  3. Group-Based Access Control

    • Use groups in policies
    • Configure application access based on groups
    • Implement role-based access control (RBAC)

Security Best Practices

Password Policies

  1. Configure Password Policy

    • Navigate to Admin InterfacePoliciesPolicies
    • Click CreatePassword Policy
    • Set minimum length, complexity requirements
    • Configure password expiration
  2. Apply to Flows

    • Edit password stages
    • Attach password policy
    • Enforce across all password changes

Session Management

  1. Configure Session Timeouts

    • Set in environment variables:
    Terminal window
    AUTHENTIK_SESSION__COOKIE_AGE=86400 # 24 hours
  2. Implement Session Limits

    • Limit concurrent sessions per user
    • Force logout on password change

Audit Logging

  1. Enable Audit Logging

    • Navigate to Admin InterfaceEventsEvent Rules
    • Configure event logging rules
    • Set retention policies
  2. Monitor Events

    • Review authentication attempts
    • Track policy changes
    • Monitor failed login attempts

Regular Security Updates

  • Update Authentik Regularly: Keep your installation up to date
  • Monitor Security Advisories: Subscribe to Authentik security notifications
  • Review Access Logs: Regularly review authentication logs for anomalies
  • Rotate Secrets: Periodically rotate database passwords and secret keys

Production Best Practices

High Availability Setup

For production deployments with high availability:

  1. Deploy Multiple Instances

    • Run multiple Authentik server containers
    • Configure load balancing in Klutch.sh
    • Ensure shared storage for media and templates
  2. Deploy Worker Containers

    • Run separate worker containers for background tasks
    • Scale workers based on workload
    • Monitor worker queue length
  3. Database High Availability

    • Use PostgreSQL with replication
    • Configure connection pooling
    • Implement automated backups
  4. Redis High Availability

    • Use Redis Sentinel or Cluster
    • Configure Redis persistence
    • Implement backup strategy

Performance Optimization

  1. Database Optimization

    • Enable connection pooling with PgBouncer
    • Optimize PostgreSQL configuration
    • Regular database maintenance (VACUUM, ANALYZE)
  2. Caching Configuration

    • Configure Redis cache settings
    • Implement CDN for static assets
    • Enable browser caching
  3. Resource Allocation

    • Monitor CPU and memory usage
    • Scale vertically or horizontally as needed
    • Configure appropriate worker counts

Monitoring and Alerting

Monitor your Authentik deployment:

  1. Application Health

    • Monitor health check endpoints
    • Track response times
    • Monitor error rates
  2. Database Performance

    • Track database connection count
    • Monitor query performance
    • Track database size growth
  3. Authentication Metrics

    • Monitor successful/failed login attempts
    • Track authentication latency
    • Monitor active sessions
  4. Resource Usage

    • CPU and memory utilization
    • Disk usage for volumes
    • Network throughput

Backup Strategy

Implement a comprehensive backup strategy:

  1. Database Backups

    Terminal window
    # Automated PostgreSQL backup
    pg_dump -h postgres-app.klutch.sh -p 8000 -U authentik authentik > authentik-backup-$(date +%F).sql
  2. Media and Templates Backup

    • Regularly backup /media volume
    • Backup /templates volume
    • Store backups in object storage
  3. Configuration Backup

    • Export application configurations
    • Backup flow definitions
    • Export policy configurations
    • Version control your Dockerfile and env configs
  4. Automated Backup Schedule

    • Daily database backups
    • Weekly full backups
    • Monthly archive backups
    • Test restore procedures regularly

Troubleshooting

Cannot Access Authentik Dashboard

Symptoms: Unable to reach Authentik web interface

Solutions:

  • Verify your app is running in the Klutch.sh dashboard
  • Check that the internal port is set to 9000
  • Ensure HTTP traffic type is selected
  • Review application logs for startup errors:
    Terminal window
    # View logs in Klutch.sh dashboard
  • Verify environment variables are correctly set
  • Check database connectivity

Database Connection Errors

Symptoms: Authentik fails to start, database connection errors in logs

Solutions:

  • Verify PostgreSQL is running and accessible
  • Check AUTHENTIK_POSTGRESQL__HOST and AUTHENTIK_POSTGRESQL__PORT
  • Confirm database credentials are correct
  • Test database connection:
    Terminal window
    # From another container
    psql -h postgres-app.klutch.sh -p 8000 -U authentik -d authentik
  • Check PostgreSQL logs for errors
  • Verify network connectivity between Authentik and PostgreSQL

Redis Connection Errors

Symptoms: Background tasks not running, cache errors

Solutions:

  • Verify Redis is running and accessible
  • Check AUTHENTIK_REDIS__HOST and AUTHENTIK_REDIS__PORT
  • Test Redis connection:
    Terminal window
    redis-cli -h redis-app.klutch.sh -p 8000 ping
  • Check Redis logs for errors
  • Verify network connectivity between Authentik and Redis

Authentication Not Working

Symptoms: Users cannot log in, OAuth flows failing

Solutions:

  • Verify flows are correctly configured
  • Check provider settings (redirect URIs, client credentials)
  • Review event logs in Authentik:
    • Navigate to Admin InterfaceEventsLogs
  • Verify application configuration matches provider settings
  • Check for policy denials in logs
  • Test with a simple flow first

Migration Errors

Symptoms: Database migration failures on startup

Solutions:

  • Check PostgreSQL version compatibility (11+)
  • Verify database user has necessary permissions
  • Review migration logs in application logs
  • Ensure database schema is clean
  • Try manual migration:
    Terminal window
    # In container
    ak migrate

Performance Issues

Symptoms: Slow response times, timeouts

Solutions:

  • Monitor CPU and memory usage in Klutch.sh dashboard
  • Check database performance and connection count
  • Review slow query logs in PostgreSQL
  • Scale compute resources vertically
  • Add more instances for horizontal scaling
  • Optimize database indexes
  • Review authentication flow complexity

Email Not Sending

Symptoms: Password reset emails not delivered, no email notifications

Solutions:

  • Verify SMTP configuration in environment variables
  • Test SMTP connection from container
  • Check SMTP server logs
  • Verify sender email is authorized
  • Review email logs in Authentik events
  • Test with Authentik’s test email task

SSL/TLS Issues

Symptoms: Certificate errors, HTTPS not working

Solutions:

  • Klutch.sh provides HTTPS automatically for platform domains
  • For custom domains, configure DNS correctly
  • Verify custom domain is added in Klutch.sh
  • Check certificate status in Klutch.sh dashboard
  • Ensure application is configured to trust Klutch.sh’s reverse proxy

Upgrading Authentik

To upgrade Authentik to a new version:

Preparation

  1. Backup Everything

    • Create database backup
    • Backup media and templates volumes
    • Export configuration
    • Document current version
  2. Review Release Notes

    • Check Authentik releases
    • Note breaking changes
    • Review upgrade guides
    • Check for new environment variables

Upgrade Process

  1. Update Dockerfile

    FROM ghcr.io/goauthentik/server:2024.10.1
  2. Update Environment Variables

    • Add any new required variables
    • Update deprecated variables
    • Review configuration changes
  3. Test in Staging

    • Deploy to a test environment first
    • Verify all functionality
    • Test integrations
    • Confirm migrations succeed
  4. Deploy to Production

    Terminal window
    git add Dockerfile
    git commit -m "Upgrade Authentik to version 2024.10.1"
    git push
  5. Verify Deployment

    • Check application logs
    • Verify database migrations completed
    • Test authentication flows
    • Verify integrations still work
  6. Monitor Post-Upgrade

    • Watch for errors in logs
    • Monitor performance metrics
    • Test critical applications
    • Verify user feedback

Rollback Procedure

If issues occur after upgrade:

  1. Restore Database Backup

    Terminal window
    psql -h postgres-app.klutch.sh -p 8000 -U authentik authentik < authentik-backup-pre-upgrade.sql
  2. Revert Dockerfile

    Terminal window
    git revert HEAD
    git push
  3. Verify Rollback

    • Check application starts correctly
    • Test authentication
    • Verify data integrity

Advanced Configuration

Custom Attribute Mapping

Map user attributes from external sources:

  1. Create Property Mapping

    • Navigate to Admin InterfaceCustomizationProperty Mappings
    • Click Create
    • Define mapping expressions
  2. Example: Map Custom Attributes

    # In property mapping expression
    return {
    "department": request.user.attributes.get("department", ""),
    "employee_id": request.user.attributes.get("employee_id", ""),
    }
  3. Apply to Provider

    • Edit OAuth2/SAML provider
    • Add property mappings
    • Test with your application

Policy Engine

Implement fine-grained access control:

  1. Expression Policy

    # Allow access only for specific group
    return ak_is_group_member(request.user, name="Admins")
  2. Reputation Policy

    • Track failed authentication attempts
    • Automatically block suspicious IPs
    • Configure threshold and duration
  3. Event Matcher Policy

    • Trigger actions based on events
    • Send notifications
    • Automate responses

API Integration

Automate Authentik management with the API:

  1. Generate API Token

    • Navigate to Admin InterfaceDirectoryTokens
    • Click Create
    • Set intent and expiration
  2. Example: Create User via API

    Terminal window
    curl -X POST https://example-app.klutch.sh/api/v3/core/users/ \
    -H "Authorization: Bearer YOUR_API_TOKEN" \
    -H "Content-Type: application/json" \
    -d '{
    "username": "newuser",
    "name": "New User",
    "email": "newuser@example.com",
    "is_active": true
    }'
  3. Example: List Applications

    Terminal window
    curl -X GET https://example-app.klutch.sh/api/v3/core/applications/ \
    -H "Authorization: Bearer YOUR_API_TOKEN"

Webhooks and Notifications

Configure webhooks for external integrations:

  1. Create Webhook Notification

    • Navigate to Admin InterfaceEventsNotification Rules
    • Click Create
    • Configure webhook URL and events
  2. Example Webhook Payload

    {
    "event": "user_login",
    "user": "john.doe",
    "timestamp": "2024-01-15T10:30:00Z",
    "ip_address": "192.168.1.100",
    "application": "myapp"
    }

Integration Examples

Grafana

  1. Configure OAuth2 in Grafana
    [auth.generic_oauth]
    enabled = true
    name = Authentik
    allow_sign_up = true
    client_id = YOUR_CLIENT_ID
    client_secret = YOUR_CLIENT_SECRET
    scopes = openid profile email
    auth_url = https://example-app.klutch.sh/application/o/authorize/
    token_url = https://example-app.klutch.sh/application/o/token/
    api_url = https://example-app.klutch.sh/application/o/userinfo/

Nextcloud

  1. Install OpenID Connect App in Nextcloud
  2. Configure Provider in Authentik
  3. Configure Nextcloud:
    • Client ID and Secret from Authentik
    • Discovery URL: https://example-app.klutch.sh/application/o/.well-known/openid-configuration

GitLab

  1. Add OAuth2 Application in GitLab
  2. Configure Provider in Authentik with GitLab’s redirect URI
  3. Users can login with Authentik SSO

Kubernetes

  1. Configure OIDC in Kubernetes API server
  2. Use kubectl with OIDC authentication
  3. Deploy Authentik Proxy for applications in Kubernetes

Additional Resources


Conclusion

Deploying Authentik to Klutch.sh with Docker provides a powerful, flexible, self-hosted identity provider solution with comprehensive SSO capabilities, advanced authentication flows, and enterprise-grade features. By following this guide, you’ve set up a production-ready Authentik instance with proper data persistence, external database configuration, security best practices, and scalability options. Your identity provider is now ready to secure your applications, manage users and groups, and provide seamless single sign-on experiences across your infrastructure.