Back to articles
Security & Anti-DDoS

Building a Comprehensive API Security System on VPS with Cloudflare Access and JWT Validation in Caddy

This guide demonstrates how to build a comprehensive API security system on a VPS by integrating Cloudflare Access for identity-based user access control and JWT validation in the...

DPTCloud Engineering6 min read
Building a Comprehensive API Security System on VPS with Cloudflare Access and JWT Validation in Caddy

Image credit: Elchinator · Pixabay Content License

This guide demonstrates how to build a comprehensive API security system on a VPS by integrating Cloudflare Access for identity-based user access control and JWT validation in the Caddy Web Server. It ensures only authorized users can access API endpoints, leveraging Cloudflare's security features and Caddy's performance for a secure, efficient, and maintainable infrastructure. The guide covers environment setup, Caddy configuration with JWT plugin, Cloudflare Access integration, API authentication testing, troubleshooting, and security optimization.

Introduction and Objectives

In the rapidly evolving landscape of web applications and APIs, protecting API endpoints from unauthorized access is critical. A comprehensive API security system must authenticate users and enforce access control based on roles, while defending against common attacks such as brute-force, replay, and token-based exploits. This guide outlines how to build a secure API infrastructure on a VPS using Caddy Web Server as a reverse proxy, combined with Cloudflare Access for identity-based access control and JWT (JSON Web Token) validation to ensure request integrity. The objective is to create a secure, scalable, and manageable infrastructure suitable for enterprise applications or internal systems.

Requirements and Environment Setup

To deploy this system, you need a Linux-based VPS (Ubuntu 22.04 or Debian 11 recommended), Caddy Web Server version 2.6 or higher, and a Cloudflare account. Basic knowledge of SSH, curl, and text editors is required. Caddy supports the JWT plugin via the `jwt` module and can integrate with Cloudflare Access through authentication rules. First, install Caddy on the VPS using the following command:

curl -sSL https://getcaddy.com | bash -s personal

Ensure Caddy is installed and running correctly. Then, create a Caddy configuration file (`/etc/caddy/Caddyfile`) to define access rules. You also need an API application (e.g., Node.js, Python, or Go) running on the VPS or internal server, and configure Caddy to proxy API requests to the backend application.

Integrating Cloudflare Access and JWT Authentication

Cloudflare Access enables identity-based access control for web and API applications, replacing IP-based or token-only authentication. To integrate, create an application in Cloudflare Access and configure authentication rules. In Caddy, use the `jwt` plugin to validate JWT tokens sent by users. First, install the JWT plugin by adding the following line to the `Caddyfile`:

jwt {\\n    issuer \\\"https://your-issuer.com\\\"\\n    audience \\\"api.your-domain.com\\\"\\n    key \\\"your-secret-key\\\"\\n    required\\n}

Replace `your-issuer.com`, `api.your-domain.com`, and `your-secret-key` with your actual values. Then, configure Caddy to proxy API requests to your backend application. For example:

api.your-domain.com {\\n    reverse_proxy https://localhost:8080 {\\n        header_up Host {http.request.host}\\n    }\\n    jwt\\n}

This ensures all requests to `api.your-domain.com` must include a valid JWT token. Additionally, you can integrate Cloudflare Access by configuring an authentication rule in Cloudflare to require user login before access, adding an extra layer of security that combines identity verification with token validation.

Testing and Verification

To test the system, use the curl command to send an API request with a valid JWT token. For example:

curl -H \\\"Authorization: Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiaWF0IjoxNTE2MjM5MDIyfQ.SflKxwRJSMeKKF2QT4fwpMeJf36POk6yJV_adQssw5c\\\" https://api.your-domain.com

If configured correctly, Caddy will validate the token and proxy the request to the backend. If the token is invalid or missing, Caddy returns a 401 Unauthorized error. Additionally, check Cloudflare Access to verify successful authentication and logged access attempts.

Troubleshooting and Optimization

Common issues include invalid tokens, expired tokens, or incorrect Caddy configuration. Check Caddy logs (`journalctl -u caddy`) to identify the root cause. Ensure the VPS system time is synchronized with NTP to prevent JWT validation errors due to time skew. You can also enhance security by integrating the Coraza WAF plugin to defend against OWASP Top 10 attacks, as detailed in Integrating Coraza WAF into Caddy Web Server: Steel Shield Against OWASP Top 10 Attacks. Finally, automate SSL certificate renewal using Certbot and the Cloudflare API to prevent connection errors, as explained in Guide to Automatically Renew Wildcard SSL Certificates Using Certbot and Cloudflare API on Linux VPS.

Configuration and Validation Checklist

Factor Condition Verification Method
Cloudflare Access Application and authentication rules created Check Cloudflare Access dashboard
JWT Plugin Installed and correctly configured Run `caddy validate` and review Caddy logs
JWT Token Valid and not expired Use `jwt.io` to inspect the token
Reverse Proxy Correctly configured to backend Run `curl` to API endpoint
SSL Certificate Automatically renewed Run `certbot renew --dry-run`

Assumptions Explained

It is assumed that the user has basic knowledge of Caddy, Cloudflare, and JWT. The guide does not include backend API application deployment. Values such as `issuer`, `audience`, and `key` are placeholders and must be replaced with actual values. Additionally, it is assumed the VPS has stable internet connectivity and is not blocked by firewalls or proxies.

Related infrastructure & engineering guides: Cloud VPS with L3/L4/L7 Anycast Anti-DDoS

DPTCloud Tier III Infrastructure

Recommended NVMe Cloud VPS Plans to Deploy This Setup

Enterprise RAID 10 NVMe SSDs, CMC & FPT District 9 uplinks with Anycast Anti-DDoS and 99.99% SLA.

View 22 VPS Plans
ECO · vn-02

VPS-2E

94.600 ₫ / mo

10% VAT included

  • CPU: 2 vCPU
  • RAM: 2 GB
  • SSD: 30 GB NVMe
ECO · vn-02Recommended

VPS-3E

170.500 ₫ / mo

10% VAT included

  • CPU: 2 vCPU
  • RAM: 4 GB
  • SSD: 50 GB NVMe
BASIC · vn-01Recommended

VPS-05

457.600 ₫ / mo

10% VAT included

  • CPU: 4 vCPU
  • RAM: 8 GB
  • SSD: 50 GB NVMe

Related Articles

View all
ZaloZalo SupportDiscord0384 753 478