Self-Hosting Authentik on Linux VPS in Pakistan: The Open-Source Okta & Auth0 Alternative for Dev Teams

Complete production guide to self-hosting Authentik on Linux VPS in Pakistan. Replace expensive Okta and Auth0 USD per-user subscriptions with open-source sovereign Single Sign-On (SSO), OAuth2/OIDC, LDAP proxy, and Passkey MFA.

Self-Hosting Authentik on Linux VPS in Pakistan: The Open-Source Okta & Auth0 Alternative for Dev Teams

Managing user identity, role-based access, and client authentication across a rapidly growing engineering team is one of the steepest operational challenges facing modern technology companies. In Pakistan, software houses, digital agencies, fintech contractors, and remote development studios routinely manage dozens of internal and client-facing platforms—from code repositories and CI/CD pipelines to internal staging servers, legacy management portals, and client staging environments.

For years, enterprise cloud providers like Okta, Auth0, and Microsoft Entra ID (Azure AD) dominated this space. However, their per-user, per-month pricing models, billed strictly in US Dollars, introduce severe operational friction in Pakistan. When compounded by currency volatility, banking foreign exchange limits, and mandatory tax withholdings, relying on foreign Identity-as-a-Service (IDaaS) platforms rapidly erodes agency profit margins.

Authentik provides a modern, fully open-source, sovereign alternative. Combining a high-performance Go core engine with an extensible Python ASGI API worker, PostgreSQL 16 database, and Redis cache bus, Authentik delivers enterprise-grade Single Sign-On (SSO), OAuth2/OIDC provider functionality, an embedded LDAP outpost, Forward Authentication proxying, and hardware-backed WebAuthn/Passkey multi-factor authentication.

This comprehensive guide walks through the architectural blueprint, deployment steps, proxy configurations, protocol integrations, and security hardening required to self-host Authentik on an enterprise Linux VPS in Pakistan.


Economic Realities and Data Sovereignty in Pakistan

The Dollar Cost of Per-Seat Identity SaaS

Proprietary IDaaS solutions charge between $3.00 and $6.00 per user each month for basic workforce identity tiers. Enterprise features such as custom password policies, advanced audit logging, and LDAP directory integration frequently push costs beyond $10.00 to $15.00 per user monthly.

For a mid-sized Pakistani software house employing 80 software developers, QA testers, project managers, and DevOps personnel, an identity bill of $480 to $1,200 per month creates significant financial and administrative burdens:

  • State Bank Advance Withholding Taxes: Pakistani financial regulations require commercial banks to deduct advance withholding tax (ranging from 5% for active tax filers up to 10% or more for non-filers) on cross-border payments charged to corporate credit cards.
  • Card Limits and Foreign Exchange Caps: Corporate debit and credit cards issued by local banks (such as HBL, Meezan, MCB, or Standard Chartered) often hit rolling monthly limits for international SaaS subscriptions, risking sudden account suspensions when invoices fail to clear.
  • Rupee Depreciation Impact: Every downward fluctuation in the USD-to-PKR exchange rate directly inflates operational overhead without adding a single unit of software value.
  • Predictable Local Billing: Running a self-hosted identity cluster on a high-bandwidth Linux VPS locks infrastructure expenditures into fixed, transparent costs, completely bypassing foreign credit card quotas and FX tax surcharges.

Identity Directory Sovereignty and Intellectual Property

Beyond pricing, an identity provider stores an organization’s most critical asset: the complete directory of engineering personnel, authentication tokens, API keys, group privileges, and client infrastructure credentials.

When outsourcing identity storage to multi-tenant cloud SaaS providers in foreign jurisdictions, Pakistani IT exporters risk client contract disputes regarding data residency, compliance audits (such as GDPR or ISO 27001), and supply chain exposure. Hosting your identity directory on dedicated, private virtual instances ensures that your authentication logs, hashes, and employee directories remain strictly under your engineering control.


Technical Architecture of Authentik

Authentik is engineered as a modular, decoupled microservice architecture optimized for speed, fault isolation, and horizontal scale.

                    +---------------------------------------------------+
                    |                 Nginx Ingress / SSL               |
                    |              (Port 443 HTTPS / HTTP2)             |
                    +-------------------------+-------------------------+
                                              |
                             Reverse Proxy & WebSocket Flow
                                              |
                    +-------------------------v-------------------------+
                    |                Authentik Core Server              |
                    |              (Go Web Server & Router)             |
                    |              Listening on Port 9000               |
                    +--------------------+-------------+----------------+
                                         |             |
                         Internal ASGI   |             | Background Tasks
                         Task Dispatch   |             | (Celery / Events)
                                         |             |
                    +--------------------v--+       +--v----------------+
                    | Authentik API Worker  |       | Redis In-Memory   |
                    |  (Python ASGI Core)   |<----->| Cache & Bus       |
                    +-----------+-----------+       +-------------------+
                                |
                        SQL Read/Write Queries
                                |
                    +-----------v-----------+
                    |     PostgreSQL 16     |
                    |  (Persistent Storage) |
                    +-----------------------+
                                |
        +-----------------------+-----------------------+
        |                                               |
+-------v-----------------------+       +---------------v---------------+
|    Forward Auth Outpost       |       |       LDAP Outpost Proxy      |
|  (Nginx / Traefik Middleware) |       |  (Legacy OpenLDAP / AD Apps)  |
+-------------------------------+       +-------------------------------+

Architectural Components

  1. Authentik Server (Go Core): Handles inbound HTTP and WebSocket connections, validates active sessions, serves the responsive Svelte frontend interface, and routes protocol requests with sub-millisecond overhead.
  2. Authentik Worker (Python ASGI / Celery): Executes background automation, identity policy evaluations, outbound email deliveries, OAuth2 client credential exchanges, and cryptographic key generation routines.
  3. PostgreSQL 16: Stores relational identity schemas, user profiles, cryptographic public keys, access tokens, group hierarchies, and structured security event logs.
  4. Redis: Functions as a low-latency pub/sub message bus, task queue coordinator, and user session cache to prevent database connection saturation during peak login bursts.
  5. Authentik Outposts: Specialized reverse-proxy and protocol translation daemon instances. Outposts can run embedded within the server or as isolated containers, facilitating forward authentication for legacy web applications and translating modern OIDC tokens into standard LDAP queries for older software stacks.

To ensure uninterrupted authentication response times and rapid background task processing, select your virtual server based on the active user profile:

Team Size / Scope Recommended vCPU RAM Storage Allocation Database Location Target Environment
1 - 50 Users 2 vCPUs 4 GB 50 GB NVMe Embedded Container Small Agency / Staging Stacks
50 - 300 Users 4 vCPUs 8 GB 100 GB NVMe Colocated PostgreSQL 16 Growing Software House
300 - 1,000 Users 8 vCPUs 16 GB 200 GB NVMe Dedicated Postgres Container Enterprise Dev Organization
1,000+ Enterprise Users Bare-Metal 32 GB+ Enterprise RAID NVMe Dedicated DB Instance High-Concurrence SSO Clusters

For baseline installations, a high-performance 4 GB or 8 GB RAM Linux VPS provides sufficient memory buffers for the Python worker and Redis cache without entering memory swap thrashing.


Production Deployment on Ubuntu 24.04 / 22.04 LTS

Step 1: System Preparation and Docker Engine Installation

Connect to your clean Ubuntu instance via SSH, update system packages, and install the Docker CE runtime and Compose plugin:

# Update local package indexes
sudo apt-get update && sudo apt-get upgrade -y

# Install essential dependencies
sudo apt-get install -y ca-certificates curl gnupg lsb-release ufw pwgen

# Add Docker official GPG key
sudo mkdir -p /etc/apt/keyrings
curl -fsSL https://download.docker.com/linux/ubuntu/gpg | sudo gpg --dearmor -o /etc/apt/keyrings/docker.gpg

# Set up the stable repository
echo \
  "deb [arch=$(dpkg --print-architecture) signed-by=/etc/apt/keyrings/docker.gpg] https://download.docker.com/linux/ubuntu \
  $(lsb_release -cs) stable" | sudo tee /etc/apt/sources.list.d/docker.list > /dev/null

# Install Docker Engine and Compose plugin
sudo apt-get update
sudo apt-get install -y docker-ce docker-ce-cli containerd.io docker-compose-plugin

# Verify Docker daemon is running
sudo systemctl enable --now docker

Step 2: Directory Structure and Environment Secrets

Create a dedicated system directory for Authentik and generate cryptographically secure tokens:

# Create application root directory
sudo mkdir -p /opt/authentik
cd /opt/authentik

# Generate secure cryptographic secrets
PG_PASS=$(pwgen -s 48 1)
AUTH_SECRET=$(pwgen -s 64 1)

Create the .env file within /opt/authentik/.env:

# /opt/authentik/.env

# PostgreSQL Configuration
PG_PASS=REPLACE_WITH_GENERATED_PG_PASS
PG_USER=authentik
PG_DB=authentik

# Authentik Core Secrets
AUTHENTIK_SECRET_KEY=REPLACE_WITH_GENERATED_AUTH_SECRET
AUTHENTIK_ERROR_REPORTING__ENABLED=false

# Core Ports (Bound to localhost for reverse proxy security)
COMPOSE_PORT_HTTP=127.0.0.1:9000

# Docker Socket Access for Embedded Outposts
AUTHENTIK_DOCKER__SOCKET=/var/run/docker.sock

# Domain Configuration
AUTHENTIK_HOST=https://auth.youragency.pk

Ensure file permissions are restricted to prevent unauthorized user inspection:

sudo chmod 600 /opt/authentik/.env

Step 3: Production Docker Compose Configuration

Create /opt/authentik/docker-compose.yml with health checks, memory reservations, and persistent volumes:

services:
  postgresql:
    image: docker.io/library/postgres:16-alpine
    restart: unless-stopped
    healthcheck:
      test: ["CMD-SHELL", "pg_isready -d $${POSTGRES_DB} -U $${POSTGRES_USER}"]
      start_period: 20s
      interval: 30s
      timeout: 5s
      retries: 5
    volumes:
      - database:/var/lib/postgresql/data
    environment:
      POSTGRES_PASSWORD: ${PG_PASS}
      POSTGRES_USER: ${PG_USER}
      POSTGRES_DB: ${PG_DB}
    networks:
      - authentik-internal

  redis:
    image: docker.io/library/redis:alpine
    command: --save 60 1 --loglevel warning
    restart: unless-stopped
    healthcheck:
      test: ["CMD-SHELL", "redis-cli ping | grep PONG"]
      start_period: 20s
      interval: 30s
      timeout: 3s
      retries: 5
    volumes:
      - redis:/data
    networks:
      - authentik-internal

  server:
    image: ghcr.io/goauthentik/server:2024.8.3
    restart: unless-stopped
    command: server
    environment:
      AUTHENTIK_REDIS__HOST: redis
      AUTHENTIK_POSTGRESQL__HOST: postgresql
      AUTHENTIK_POSTGRESQL__USER: ${PG_USER}
      AUTHENTIK_POSTGRESQL__NAME: ${PG_DB}
      AUTHENTIK_POSTGRESQL__PASSWORD: ${PG_PASS}
      AUTHENTIK_SECRET_KEY: ${AUTHENTIK_SECRET_KEY}
      AUTHENTIK_ERROR_REPORTING__ENABLED: ${AUTHENTIK_ERROR_REPORTING__ENABLED}
    volumes:
      - ./media:/media
      - ./custom-templates:/templates
    ports:
      - "${COMPOSE_PORT_HTTP}:9000"
    depends_on:
      postgresql:
        condition: service_healthy
      redis:
        condition: service_healthy
    networks:
      - authentik-internal

  worker:
    image: ghcr.io/goauthentik/server:2024.8.3
    restart: unless-stopped
    command: worker
    environment:
      AUTHENTIK_REDIS__HOST: redis
      AUTHENTIK_POSTGRESQL__HOST: postgresql
      AUTHENTIK_POSTGRESQL__USER: ${PG_USER}
      AUTHENTIK_POSTGRESQL__NAME: ${PG_DB}
      AUTHENTIK_POSTGRESQL__PASSWORD: ${PG_PASS}
      AUTHENTIK_SECRET_KEY: ${AUTHENTIK_SECRET_KEY}
      AUTHENTIK_ERROR_REPORTING__ENABLED: ${AUTHENTIK_ERROR_REPORTING__ENABLED}
    user: root
    volumes:
      - /var/run/docker.sock:/var/run/docker.sock
      - ./media:/media
      - ./certs:/certs
      - ./custom-templates:/templates
    depends_on:
      postgresql:
        condition: service_healthy
      redis:
        condition: service_healthy
    networks:
      - authentik-internal

volumes:
  database:
    driver: local
  redis:
    driver: local

networks:
  authentik-internal:
    driver: bridge

Start the stack in detached mode:

cd /opt/authentik
docker compose up -d

Monitor initial database migration logs until the services report healthy status:

docker compose logs -f server

Nginx Reverse Proxy and SSL Termination

Never expose the Authentik core server directly to public interfaces. Use a hardened Nginx reverse proxy with TLS 1.3 encryption, HTTP/2 support, WebSocket upgrade handling, and security headers.

Step 1: Install Nginx and Certbot

sudo apt-get install -y nginx certbot python3-certbot-nginx

Step 2: Configure Virtual Host

Create /etc/nginx/sites-available/authentik.conf:

# Map for WebSocket Upgrade Handshake
map $http_upgrade $connection_upgrade {
    default upgrade;
    ''      close;
}

server {
    listen 80;
    listen [::]:80;
    server_name auth.youragency.pk;

    location /.well-known/acme-challenge/ {
        root /var/www/certbot;
    }

    location / {
        return 301 https://$host$request_uri;
    }
}

server {
    listen 443 ssl http2;
    listen [::]:443 ssl http2;
    server_name auth.youragency.pk;

    # SSL Certificates (managed via Certbot)
    ssl_certificate /etc/letsencrypt/live/auth.youragency.pk/fullchain.pem;
    ssl_certificate_key /etc/letsencrypt/live/auth.youragency.pk/privkey.pem;

    # Modern TLS Security Parameters
    ssl_protocols TLSv1.2 TLSv1.3;
    ssl_ciphers ECDHE-ECDSA-AES128-GCM-SHA256:ECDHE-RSA-AES128-GCM-SHA256:ECDHE-ECDSA-AES256-GCM-SHA384:ECDHE-RSA-AES256-GCM-SHA384:ECDHE-ECDSA-CHACHA20-POLY1305:ECDHE-RSA-CHACHA20-POLY1305;
    ssl_prefer_server_ciphers off;
    ssl_session_timeout 1d;
    ssl_session_cache shared:SSL:10m;
    ssl_session_tickets off;

    # Security Headers
    add_header X-Frame-Options "SAMEORIGIN" always;
    add_header X-Content-Type-Options "nosniff" always;
    add_header Referrer-Policy "strict-origin-when-cross-origin" always;
    add_header Strict-Transport-Security "max-age=63072000; includeSubDomains; preload" always;

    # Buffer and Timeout Adjustments
    client_max_body_size 50M;
    proxy_buffers 8 16k;
    proxy_buffer_size 32k;

    location / {
        proxy_pass http://127.0.0.1:9000;
        proxy_http_version 1.1;

        # WebSocket Proxy Support
        proxy_set_header Upgrade $http_upgrade;
        proxy_set_header Connection $connection_upgrade;

        # Upstream Headers
        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;
        proxy_set_header X-Forwarded-Server $host;

        proxy_read_timeout 90s;
    }
}

Obtain a production SSL certificate with Certbot and enable the site:

# Obtain Let's Encrypt Certificate
sudo certbot certonly --nginx -d auth.youragency.pk

# Enable site configuration
sudo ln -s /etc/nginx/sites-available/authentik.conf /etc/nginx/sites-enabled/
sudo nginx -t && sudo systemctl reload nginx

Navigate to https://auth.youragency.pk/if/flow/initial-setup/ to configure the primary administrative password and superuser profile.


Protecting Legacy Applications with Forward Auth

A major advantage of Authentik over proprietary SaaS providers is its Forward Auth Outpost. Many development teams maintain legacy internal web tools, custom PHP interfaces, phpMyAdmin databases, or cPanel staging links that lack native OIDC or SAML capabilities.

Forward Auth intercepts inbound HTTP requests at the Nginx reverse proxy level, verifies authentication status against Authentik, and only forwards authorized traffic to the backend application without altering a single line of application source code.

+-------------+         1. GET /dashboard
| User Client | -------------------------------------------------+
+------+------+                                                  |
       ^                                                         |
       | 4. Return Protected App Content                         v
       |                                                +----------------+
       |                                                | Nginx Ingress  |
       |                                                +-------+--------+
       |                                                        |
       |                   2. Subrequest: GET /outpost.goauthentik.io/auth/nginx
       |                                                        v
       |                                                +----------------+
       |   3. 200 OK (User Authenticated & Authorized)  | Authentik      |
       |      or 302 Redirect to Login Flow             | Outpost Proxy  |
       |                                                +----------------+
       |                                                        |
       |                                                        | (If 200 OK)
       |                                                        v
       +------------------------------------------------+----------------+
                                                        | Upstream App   |
                                                        | (e.g. Port 8080|
                                                        +----------------+

Implementing Forward Auth in Nginx

To protect an internal tool running on tools.youragency.pk:

  1. In Authentik Admin: Navigate to Applications -> Providers -> Create Proxy Provider.
    • Mode: Forward auth (single application)
    • External Host: https://tools.youragency.pk
  2. Add the Provider to a new Application and bind it to the Embedded Outpost.
  3. In Nginx, apply the following configuration to the target application:
server {
    listen 443 ssl http2;
    server_name tools.youragency.pk;

    ssl_certificate /etc/letsencrypt/live/tools.youragency.pk/fullchain.pem;
    ssl_certificate_key /etc/letsencrypt/live/tools.youragency.pk/privkey.pem;

    # Authentik Forward Auth Authentication Endpoint
    location /outpost.goauthentik.io {
        proxy_pass http://127.0.0.1:9000/outpost.goauthentik.io;
        proxy_set_header Host $host;
        proxy_set_header X-Original-URL $scheme://$http_host$request_uri;
        add_header Set-Cookie $upstream_http_set_cookie;
        proxy_pass_request_body off;
        proxy_set_header Content-Length "";
    }

    # Intercept Unauthorized Requests and Route to Authentik Login
    location @goauthentik_proxy_signin {
        return 302 /outpost.goauthentik.io/start?rd=$scheme://$http_host$request_uri;
    }

    # Protected Application Route
    location / {
        # Check authentication status via subrequest
        auth_request /outpost.goauthentik.io/auth/nginx;
        error_page 401 = @goauthentik_proxy_signin;

        # Forward user metadata in headers to upstream backend
        auth_request_set $authentik_username $upstream_http_x_authentik_username;
        auth_request_set $authentik_email $upstream_http_x_authentik_email;
        proxy_set_header X-Forwarded-User $authentik_username;
        proxy_set_header X-Forwarded-Email $authentik_email;

        # Forward to internal legacy service
        proxy_pass http://127.0.0.1:8080;
        proxy_set_header Host $host;
        proxy_set_header X-Real-IP $remote_addr;
    }
}

Any unauthenticated engineer visiting tools.youragency.pk is transparently redirected to your Authentik login portal, prompted for MFA, and returned to their target page upon successful authentication.


OIDC & OAuth2 Integration Blueprints

OpenID Connect (OIDC) is the gold standard for connecting developer platforms to a central identity provider. Below are production configurations for the five most common platforms used by Pakistani engineering teams.

1. Gitea (Self-Hosted Git Service)

In Authentik:

  • Create OAuth2/OpenID Provider:
    • Name: Gitea
    • Client Type: Confidential
    • Redirect URIs: https://git.youragency.pk/user/oauth2/authentik/callback
    • Scopes: openid, profile, email
  • Note the Client ID and Client Secret.

In Gitea app.ini configuration:

[oauth2_client]
ENABLE = true

[auth.oauth2]
ENABLE = true

Or configure via Gitea Admin -> Authentication Sources -> Add New:

  • Authentication Type: OAuth2
  • Authentication Name: Authentik SSO
  • OAuth2 Provider: OpenID Connect
  • Client ID: <AUTHENTIK_CLIENT_ID>
  • Client Secret: <AUTHENTIK_CLIENT_SECRET>
  • OpenID Connect Auto Discovery URL: https://auth.youragency.pk/application/o/gitea/.well-known/openid-configuration

2. Nextcloud (Enterprise Document and Asset Storage)

In Nextcloud, install the official user_oidc application via administrative settings or CLI:

docker exec -u www-data nextcloud php occ app:enable user_oidc

Register the Authentik identity provider:

docker exec -u www-data nextcloud php occ user_oidc:provider authentik \
  --clientid="<AUTHENTIK_CLIENT_ID>" \
  --clientsecret="<AUTHENTIK_CLIENT_SECRET>" \
  --discoveryuri="https://auth.youragency.pk/application/o/nextcloud/.well-known/openid-configuration" \
  --scope="openid email profile"

3. Grafana (Infrastructure Observability)

Add the following environment variables to your Grafana Docker Compose or /etc/grafana/grafana.ini configuration:

[auth.generic_oauth]
enabled = true
name = Authentik
allow_sign_up = true
client_id = <AUTHENTIK_CLIENT_ID>
client_secret = <AUTHENTIK_CLIENT_SECRET>
scopes = openid profile email groups
auth_url = https://auth.youragency.pk/application/o/authorize/
token_url = https://auth.youragency.pk/application/o/token/
api_url = https://auth.youragency.pk/application/o/userinfo/
role_attribute_path = contains(groups[*], 'DevOps Admins') && 'Admin' || contains(groups[*], 'Developers') && 'Editor' || 'Viewer'

This configuration dynamically maps Authentik user group memberships directly to Grafana Viewer, Editor, or Admin roles.

4. Portainer (Docker Container Management)

In Portainer:

  1. Navigate to Settings -> Authentication.
  2. Select OAuth.
  3. Choose Custom OAuth Provider:
    • Client ID: <AUTHENTIK_CLIENT_ID>
    • Client Secret: <AUTHENTIK_CLIENT_SECRET>
    • Authorization URL: https://auth.youragency.pk/application/o/authorize/
    • Access token URL: https://auth.youragency.pk/application/o/token/
    • Resource URL: https://auth.youragency.pk/application/o/userinfo/
    • User identifier: preferred_username
    • Scopes: openid email profile

5. Plane (Open-Source Jira / Linear Alternative)

For product management and sprint tracking in Plane, set the following environment variables in Plane’s .env:

OIDC_CLIENT_ID=<AUTHENTIK_CLIENT_ID>
OIDC_CLIENT_SECRET=<AUTHENTIK_CLIENT_SECRET>
OIDC_WELL_KNOWN_URL=https://auth.youragency.pk/application/o/plane/.well-known/openid-configuration
ENABLE_OIDC=1

Security Hardening and MFA Policies

An identity provider represents the root of trust across your entire infrastructure. Hardening Authentik against credential stuffing, phishing, and session hijacking is non-negotiable.

1. Enforcing WebAuthn / FIDO2 Passkeys

Traditional SMS and time-based OTP codes are increasingly vulnerable to real-time reverse proxy phishing attacks (e.g., Evilginx). Authentik natively supports hardware-bound WebAuthn and cryptographic Passkeys (YubiKeys, TouchID, Windows Hello):

  1. In Authentik Admin: Open Flows and Stages -> Stages.
  2. Edit the Default Authenticator Validation Stage.
  3. Under Device Classes, configure WebAuthn Authenticators as primary.
  4. Set User Verification to Required (requiring biometric confirmation or hardware PIN).
  5. Require all engineers handling production credentials to enroll at least one primary and one backup hardware Passkey.

2. IP Throttling and Brute-Force Rate Limiting

Protect the /if/flow/default-authentication-flow/ endpoint from automated credential brute-forcing by configuring rate limiting in your Nginx configuration:

# Define rate limiting zone based on client IP
limit_req_zone $binary_remote_addr zone=auth_limit:10m rate=5r/s;

server {
    ...
    location /if/flow/ {
        limit_req zone=auth_limit burst=10 nodelay;
        proxy_pass http://127.0.0.1:9000;
        ...
    }
}

3. Linux Firewall Isolation (UFW)

Ensure that all internal microservice ports (PostgreSQL 5432, Redis 6379, and Authentik Core 9000) are completely inaccessible from public network interfaces:

# Block all incoming by default
sudo ufw default deny incoming
sudo ufw default allow outgoing

# Allow only SSH and Web Traffic
sudo ufw allow 22/tcp
sudo ufw allow 80/tcp
sudo ufw allow 443/tcp

# Enable Firewall
sudo ufw enable

Automated Disaster Recovery and Secret Rotation

Automated PostgreSQL Cold Backups

Because Authentik stores all cryptographic signing certificates, active session states, and user hashes in PostgreSQL, regular automated backups are vital.

Create /opt/authentik/scripts/backup.sh:

#!/usr/bin/env bash
set -eo pipefail

BACKUP_DIR="/var/backups/authentik"
TIMESTAMP=$(date +"%Y%m%d_%H%M%S")
BACKUP_FILE="${BACKUP_DIR}/authentik_db_${TIMESTAMP}.sql.gz"

mkdir -p "${BACKUP_DIR}"

# Execute pg_dump directly through Docker container
docker compose -f /opt/authentik/docker-compose.yml exec -T postgresql \
  pg_dump -U authentik -d authentik | gzip > "${BACKUP_FILE}"

# Restrict permissions
chmod 600 "${BACKUP_FILE}"

# Delete backups older than 30 days
find "${BACKUP_DIR}" -type f -name "*.sql.gz" -mtime +30 -delete

echo "[${TIMESTAMP}] Authentik database backup completed: ${BACKUP_FILE}"

Make the script executable and schedule it in root’s crontab:

sudo chmod +x /opt/authentik/scripts/backup.sh
# Run nightly at 02:00 AM PKT
(crontab -l 2>/dev/null; echo "0 2 * * * /opt/authentik/scripts/backup.sh >> /var/log/authentik_backup.log 2>&1") | crontab -

Secret Rotation Runbook

If an administrative secret or AUTHENTIK_SECRET_KEY is suspected of compromise:

  1. Generate a new secret key:
    NEW_KEY=$(pwgen -s 64 1)
  2. Update AUTHENTIK_SECRET_KEY in /opt/authentik/.env.
  3. Restart the worker and server containers:
    docker compose down && docker compose up -d
  4. Regenerate OAuth2 Client Secrets across active application providers in the Authentik Admin interface.
  5. Invalidate all active user sessions under Directory -> Users -> Select All -> Revoke Access Tokens / End Sessions.

Hardware Scaling: From Linux VPS to Dedicated Bare-Metal

For small to mid-sized technology teams (up to 300 active users), a high-speed Linux VPS provides exceptional price-to-performance, fast NVMe I/O, and low latency.

However, as software export houses scale past 1,000+ active enterprise developers, run dozens of CI/CD runner pipelines, and operate high-frequency LDAP forward proxies, virtualization overhead and hypervisor “noisy neighbor” contention can introduce latency spikes during morning login peaks and automated deployments.

Scaling Bottlenecks in Virtualized Environments

  • CPU Steal During Token Validation: JWT signing, RSA cryptographic verification, and PBKDF2/Argon2 password hashing place bursty demands on CPU cores. Shared hypervisor threads can experience CPU steal, introducing visible 300ms–800ms delays in API gateway token validation.
  • I/O Bottlenecks on Event Auditing: Every user interaction, API token validation, and proxy check generates structured audit events in PostgreSQL. Under high load, shared storage pools can bottleneck on write IOPS.
+-----------------------------------------------------------------------------------+
|                        INFRASTRUCTURE SCALING PATHWAY                             |
+-----------------------------------------------------------------------------------+
| 1. High-Performance Linux VPS (1 to 300 Users)                                    |
|    - Isolated Virtual CPU Cores                                                   |
|    - High-Speed NVMe Storage                                                      |
|    - Ideal for agile teams, internal tools, and staging SSO                      |
+-----------------------------------------------------------------------------------+
                                          |
                                          v
+-----------------------------------------------------------------------------------+
| 2. Unmetered Dedicated Bare-Metal Servers (300 to 1,000+ Users)                  |
|    - Zero Hypervisor Abstraction & Zero CPU Contention                            |
|    - Dedicated Hardware PCIe 4.0 NVMe RAID Arrays                                 |
|    - Unmetered High-Bandwidth Port Profiles                                       |
|    - Enterprise Deployment: [Dedicated Servers](/servers/dedicated)              |
+-----------------------------------------------------------------------------------+
                                          |
                                          v
+-----------------------------------------------------------------------------------+
| 3. Domestic Low-Latency Bare-Metal Infrastructure                                 |
|    - Local Pakistan Data Center Peering (PTCL, Nayatel, StormFiber, Transworld)    |
|    - Sub-15ms Round-Trip Response Times for Domestic Engineering Offices          |
|    - Enterprise Deployment: [Dedicated Servers in Pakistan](/servers/dedicated-Pakistan)|
+-----------------------------------------------------------------------------------+

When to Migrate to Bare-Metal

When identity verification scales to cross-office engineering operations, migrating your identity cluster to enterprise Dedicated Servers delivers critical architectural advantages:

  • Dedicated Physical Cores: Raw, unshared Intel Xeon or AMD EPYC execution pipelines guarantee zero latency degradation during intensive cryptographic hashing operations.
  • Hardware NVMe RAID Arrays: Direct PCI Express storage arrays deliver hundreds of thousands of sustained IOPS, ensuring instantaneous event logging and zero-downtime database vacuuming.
  • Local Network Peering: Deploying on Dedicated Servers in Pakistan routes corporate traffic directly through domestic internet exchanges (such as PIX) and regional carriers (Nayatel, PTCL, StormFiber, Transworld, and Jazz). This cuts round-trip authentication handshakes for domestic engineering teams to under 15 milliseconds, compared to 140ms+ for servers hosted in Europe or North America.

Production Security and Maintenance Checklist

Before onboarding your agency’s development team to your self-hosted Authentik cluster, complete this final verification checklist:

  • DNS & TLS Validation: Verify that auth.youragency.pk resolves correctly with a valid, auto-renewing Let’s Encrypt certificate.
  • Disable Outbound Error Telemetry: Ensure AUTHENTIK_ERROR_REPORTING__ENABLED=false is set in /opt/authentik/.env to maintain complete directory privacy.
  • Remove Default Admin Passwords: Complete the initial setup flow at /if/flow/initial-setup/ and securely store the akadmin credentials in an encrypted team password vault.
  • Enforce WebAuthn Passkeys: Set the authentication flow to require hardware Passkeys or TOTP authenticators for all administrative accounts.
  • Configure Automated Database Backups: Confirm that /opt/authentik/scripts/backup.sh runs via cron and verifies valid gzipped SQL dump creation.
  • Verify UFW Firewall Rules: Check that ports 5432 (Postgres), 6379 (Redis), and 9000 (Authentik Core) are closed to the public internet and only ports 80, 443, and 22 are open.
  • Audit Session Expiry Policies: Configure reasonable session token timeouts (e.g., 8 to 12 hours) to prevent orphaned sessions on remote employee workstations.

Conclusion

Self-hosting Authentik on a Linux VPS allows Pakistani software houses, digital agencies, and engineering teams to escape exorbitant per-seat USD SaaS subscriptions, avoid domestic foreign exchange tax deductions, and establish complete sovereignty over their identity data. With native support for modern OIDC, legacy forward auth proxying, and hardware-backed Passkeys, Authentik delivers the full capabilities of enterprise identity providers without the recurring financial overhead.

SOVEREIGN IDENTITY CLOUD INFRASTRUCTURE

Deploy Production-Ready Linux VPS for Authentik SSO

Eliminate recurring USD SaaS fees for Okta and Auth0. Host Authentik, OpenID Connect, and internal developer tooling on NextGen high-speed Linux VPS nodes with pure NVMe storage, dedicated static IPv4, and 24/7 senior infrastructure engineering support in Pakistan.