惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

酷 壳 – CoolShell
酷 壳 – CoolShell
P
Privacy & Cybersecurity Law Blog
G
GRAHAM CLULEY
T
The Exploit Database - CXSecurity.com
www.infosecurity-magazine.com
www.infosecurity-magazine.com
Threat Intelligence Blog | Flashpoint
Threat Intelligence Blog | Flashpoint
Project Zero
Project Zero
S
Security @ Cisco Blogs
TaoSecurity Blog
TaoSecurity Blog
A
Arctic Wolf
Webroot Blog
Webroot Blog
Hacker News - Newest:
Hacker News - Newest: "LLM"
Security Latest
Security Latest
H
Heimdal Security Blog
N
News and Events Feed by Topic
N
News | PayPal Newsroom
T
Tor Project blog
OSCHINA 社区最新新闻
OSCHINA 社区最新新闻
GbyAI
GbyAI
The Last Watchdog
The Last Watchdog
Y
Y Combinator Blog
宝玉的分享
宝玉的分享
Scott Helme
Scott Helme
A
About on SuperTechFans
M
MIT News - Artificial intelligence
V
V2EX
V
Visual Studio Blog
Recorded Future
Recorded Future
博客园 - 叶小钗
F
Fortinet All Blogs
L
Lohrmann on Cybersecurity
The GitHub Blog
The GitHub Blog
博客园 - Franky
P
Proofpoint News Feed
MyScale Blog
MyScale Blog
D
Darknet – Hacking Tools, Hacker News & Cyber Security
S
Secure Thoughts
D
DataBreaches.Net
Cyber Security Advisories - MS-ISAC
Cyber Security Advisories - MS-ISAC
博客园 - 三生石上(FineUI控件)
I
InfoQ
SecWiki News
SecWiki News
Blog — PlanetScale
Blog — PlanetScale
Engineering at Meta
Engineering at Meta
J
Java Code Geeks
B
Blog RSS Feed
AWS News Blog
AWS News Blog
Know Your Adversary
Know Your Adversary
V
Vulnerabilities – Threatpost
H
Help Net Security

DEV Community

Authentication Security Deep Dive: From Brute Force to Salted Hashing (With Java Examples) Why AI Systems Don’t Fail — They Drift Spilling beans for how i learn for exam😁"Reinforcement Learning Cheat Sheet" I Replaced Chrome with Safari for AI Browser Automation. Here's What Broke (and What Finally Worked) How Python Borrows Other People's Work The $40 Architecture: Processing 1 Billion API Requests with 99.99% Uptime Vibe Coding: A Workflow Guide (From Zero to SaaS) Most webhook security guides protect the wrong side. The scary part is delivery. Headless CMS for TanStack Start: Build a Blog with Cosmic EU Age Verification App "Hacked in 2 Minutes" — What Actually Happened Comfy Cloud’s delete function does not actually remove files Running AI Models on GPU Cloud Servers: A Beginner Guide Event-driven media intelligence with AWS Step Functions and Bedrock I scored 500 AI prompts across 8 quality dimensions — here's what broke How to Call Google Gemini API from Next.js (Free Tier, No Backend Needed) The Portal Protocol: Reclaiming Human Connection in the Age of AI How to Fix Your Team's Scattered Knowledge Problem With a Self-Hosted Forum Intro to tc Cloud Functors: A Graph-First Mental Model for the Modern Cloud Designing Multi-Tenant Backends With Both Ownership and Team Access I Built a Neumorphic CSS Library with 77+ Components — Here's What I Learned PostgreSQL Performance Optimization: Why Connection Pooling Is Critical at Scale Cómo construí un SaaS multi-rubro para gestionar expensas en Argentina con FastAPI + Vue 3 🚀 I Built an Ethical Hacking Scanner Tool – Open Source Project I Replaced /usage and /context in Claude Code With a Single Statusline A Pythonic Way to Handle Emails (IMAP/SMTP) with Auto-Discovery and AI-Ready Design I Collected 8.9 Million Polymarket Price Points — Here's What I Found About How Markets Really Move EcoTrack AI — Carbon Footprint Tracker & Dashboard Everyone's Using AI. No One Agrees How. 5 self-hosted ebook managers worth trying in 2026 Building Your First AI Agent with LangChain: From Chatbot to Autonomous Assistant Common SOC 2 Failures (Real World) Stop Vibe-Checking Your AI App: A Practical Guide to Evals How to Use SonarQube and SonarScanner Locally to Level Up Your Code Quality Your Next To-Do App Is Dead — I Replaced Mine with an OpenClaw AI Sign a Nostr event in 60 lines of Python using coincurve — no nostr-sdk, no nbxplorer, no rust toolchain ITGC Audit Explained Like You’re in Big 4 Patch Tuesday abril 2026: Microsoft parcha 163 vulnerabilidades y un zero-day en SharePoint Stop scraping everything: a better way to track competitor price changes Listing on MCPize + the Official MCP Registry while routing payments OUTSIDE the marketplace — how I kept 100% of my x402 revenue Building an AI-Powered Risk Intelligence System Using Serverless Architecture Why We Ripped Function Overloading Out of Our AI Toolchain Testing AI-Generated Code: How to Actually Know If It Works SaaS Churn Is Killing Your Business. Here Is What to Do About It (Without a Support Team) The Speed of AI Is No Longer Linear - And Self-Improving Models Are Why How to Implement RBAC for MCP Tools: A Practical Guide for Engineering Teams From Standard Quote to Persuasive Proposal: AI Automation for Arborists I built a CLI that scaffolds complete multi-tenant SaaS apps Axios CVE-2025–62718: The Silent SSRF Bug That Could Be Hiding in Your Node.js App Right Now The dashboard that ended our friendship Data Pipelines Explained Simply (and How to Build Them with Python) The Hidden Cost of AI Systems Nobody Talks About. undefined vs undeclared, and how typeof behaves Switching from file-based jobs to NATS/Kafka in Rust without changing code io_uring Adventures: Rust Servers That Love Syscalls Why Agentic AI is Killing the Traditional Database The POUR principles of web accessibility for developers and designers Quantum Neural Network 3D — A Deep Dive into Interactive WebGL Visualization How To Install Caveman In Codex On macOS And Windows Automation Pipeline Reliability: Why Your Workflow Breaks When Nobody Is Watching I Built an 'Open World' AI Coding Agent — It Works From ANY Folder From Freelancing to Product: A Tech Service Company's SaaS Transformation China's AI Giants: Adding Tencent Hunyuan & ByteDance Doubao to AI University (74 Providers) On the Vibe Coders and Their Lies clerk: Auto-Summarize Your Claude Code Sessions AI Weekly — 2026/04/10–04/17 | The Model Lockdown Is Here, but the Toolchain Is the Real Battleground AI 週報 — 2026/04/10–2026/04/17 模型封鎖潮來了,但工具鏈才是真戰場 Maybe this is how Open-Source apps are born... 🚀 Fine-Tune LLMs with LoRA and QLoRA: 2026 Guide tRPC v11 + Next.js App Router: End-to-End Type Safety Without the Boilerplate ShadCN UI in 2026: Why I Stopped Installing Component Libraries and Started Owning My Components SaaS Billing in React Server Components: Stripe + Supabase Without a Single `useEffect` Join our DEV Weekend Challenge — $1,000 in Prizes Across TEN winners! Submissions Due April 20 at 6:59 AM UTC. Implementing FSRS Spaced Repetition in Flutter + Supabase — Adding Memory Science to an AI Learning App "I Texted My Localhost From the Train — Claude Code Fixed the Bug Before I Got Home" I Built a Sales Prep AI and It Went Deeper Than Expected Design to Code #2: One JSON, Eleven Outputs Solving the 100M-Row Problem: A Summary Table Pattern for High-Volume Push Notification Logs Flutter Web With Wasm: What Actually Changes For Developers I Built 50 Royalty-Free Soundtracks for My Side Project in a Weekend Using AI Music Generation The Vibe Coding Security Checklist: 7 Things to Check Before You Ship Stop Letting Googlebot Guess Fix Your React App's SEO Right Desconstruindo o Streaming do LinkedIn: Como Criar um Engine de Extração de Vídeo de Alta Performance com HLS e FFmpeg (EDA Part-1) EDA (Exploratory Data Analysis) Explained With Real Life — Why Looking at Your Data Is the Most Important Step in Machine Learning Brand Relationship Management at Scale: Our 4-Touch Outreach System for 200+ Brands Why String.fromEnvironment() Might Return an Empty String in Dart JGuardrails 1.0.0 — Hardening Java LLM Apps Against Jailbreaks, Toxicity, and Prompt Injection Plan and Schedule a Full Week of Threads Content From One Claude Conversation Coding Cat Oran Ep3, Five Tables Changed Everything Updated: BFF Pattern I'm done watching freelancers get buried by 200 proposals. So I'm building the alternative. This is my first post BFS Algorithm in Java Step by Step Tutorial with Examples Tracking LLM Pricing Monthly: An Open Dataset for 22 AI Models How We Measure Content ROI on a Comparison Site: Revenue Attribution Without Perfect Data Introducing Nova AI Ops: The AI-Native Operating System for SRE Teams I built a free desktop video downloader for Windows — Grabbit How Talkie OCR Helps Vision-Impaired & Dyslexic Users Read the World Around Them VRCFaceTracking安装和iPhone面捕配置教程,有bug Even CrowdStrike Can't See Your Agents The Automation Gold Rush: What n8n Workflows and Claude Are Opening Up for Developers Right Now
How to Secure a System with mTLS Certificates (Mutual TLS)
Oscar Ricard · 2026-04-24 · via DEV Community

In the world of modern application security, mTLS (Mutual TLS) has become a fundamental standard for protecting communications between services. Unlike traditional TLS where only the server authenticates, mTLS requires both parties (client and server) to present valid certificates, creating a much more robust security layer.

In this article, I'll show you how to implement mTLS step by step, from certificate generation to configuration in real-world applications.

Architecture savnet.co

Diagram created with https://savnet.co

What is mTLS and Why Does It Matter?

mTLS (Mutual TLS) is an extension of the standard TLS protocol that adds mutual authentication. While in traditional TLS only the server presents a certificate, in mTLS both the client and the server must authenticate each other.

Key Benefits:

  1. Strong authentication: Both ends of the communication are verified
  2. MITM attack prevention: Makes man-in-the-middle attacks significantly harder
  3. Zero Trust: Aligns perfectly with Zero Trust architectures
  4. Microservices security: Ideal for service-to-service communications

Common Use Cases:

  • Internal APIs between microservices
  • Service-to-service communication in Kubernetes
  • Payment system connections
  • Secure B2B communications
  • Sensitive API access

Step 1: Set Up the Environment

For this tutorial, we'll work on an Ubuntu server that will act as our certificate generator and Certificate Authority (CA). We only need a small server with 512MB RAM and 1 CPU, enough to generate and manage certificates.

New server

We'll need some basic tools:

# Update system
sudo apt update && sudo apt upgrade -y

# Install OpenSSL (if not already installed)
sudo apt install -y openssl curl wget

# Verify OpenSSL version
openssl version

Enter fullscreen mode Exit fullscreen mode

Version OpenSsl

For other operating systems, make sure OpenSSL is installed.

Step 2: Create the Certificate Authority (CA)

The CA is the entity that will issue and sign all our certificates. Let's create a private CA.

2.1 Create working directory

mkdir -p ~/mtls-ca
cd ~/mtls-ca
mkdir -p ca/private ca/certs ca/newcerts
mkdir -p server/private server/certs
mkdir -p client/private client/certs

# Set secure permissions
chmod 700 ca/private server/private client/private

Enter fullscreen mode Exit fullscreen mode

2.2 Generate CA private key and certificate

# Generate CA private key (password-protected)
openssl genrsa -aes256 -out ca/private/ca.key 4096

# Generate self-signed CA certificate
openssl req -new -x509 -days 7300 -sha256 \
  -key ca/private/ca.key \
  -out ca/certs/ca.crt \
  -subj "/C=US/ST=California/L=San Francisco/O=MyCompany/OU=IT/CN=MyCA-Root/emailAddress=admin@mycompany.com"

Enter fullscreen mode Exit fullscreen mode

Explanation of the -subj parameter:

  • /C=US: Country code (2 letters)
  • /ST=California: State or province
  • /L=San Francisco: Locality or city
  • /O=MyCompany: Your organization name
  • /OU=IT: Organizational unit
  • /CN=MyCA-Root: Common name of the CA
  • /emailAddress=admin@mycompany.com: Contact email

Customize these values with your actual information.

During the process you'll be prompted for:

  • A password for the private key (store it in a safe place)

2.3 Verify the CA certificate

openssl x509 -in ca/certs/ca.crt -text -noout

Enter fullscreen mode Exit fullscreen mode

You should see detailed information about your CA, including:

  • Issuer: Your own CA
  • Validity: 20 years (7300 days)
  • Key usage: Certifying other keys

Step 3: Generate Server Certificates

Now let's create certificates for our server.

3.1 Create server private key and CSR

cd ~/mtls-ca

# Generate server private key
openssl genrsa -out server/private/server.key 2048

# Create Certificate Signing Request (CSR)
openssl req -new -sha256 \
  -key server/private/server.key \
  -out server/server.csr \
  -subj "/C=US/ST=California/L=San Francisco/O=MyCompany/OU=Web/CN={YOUR DOMAIN OR IP WHERE YOUR WEB APP RUNS}"

Enter fullscreen mode Exit fullscreen mode

Customize the -subj parameter:

  • /C=US: Your country code
  • /ST=California: Your state or province
  • /L=San Francisco: Your locality or city
  • /O=MyCompany: Your organization
  • /OU=Web: Organizational unit (e.g., Web, API, etc.)
  • /CN=api.mydomain.com: IMPORTANT: Your server's domain or IP

3.2 Sign the server certificate with the CA

# Sign the server certificate
openssl x509 -req -days 365 -sha256 \
  -in server/server.csr \
  -CA ca/certs/ca.crt \
  -CAkey ca/private/ca.key \
  -CAcreateserial \
  -out server/certs/server.crt \
  -extfile <(echo -e "basicConstraints=CA:FALSE\nkeyUsage=digitalSignature,keyEncipherment\nextendedKeyUsage=serverAuth")

# Verify the signed certificate
openssl x509 -in server/certs/server.crt -text -noout

Enter fullscreen mode Exit fullscreen mode

Verificate server certificate

3.3 Create certificate chain file

# Create certificate chain for the server
cat server/certs/server.crt ca/certs/ca.crt > server/certs/server-chain.crt

Enter fullscreen mode Exit fullscreen mode

Step 4: Generate Client Certificates

Let's repeat the process for the client.

4.1 Create client private key and CSR

# Generate client private key
openssl genrsa -out client/private/client.key 2048

# Create CSR for the client
openssl req -new -sha256 \
  -key client/private/client.key \
  -out client/client.csr \
  -subj "/C=US/ST=California/L=San Francisco/O=MyCompany/OU=Clients/CN=app-client-01"

Enter fullscreen mode Exit fullscreen mode

Customize the -subj parameter:

  • /C=US: Your country code
  • /ST=California: Your state or province
  • /L=San Francisco: Your locality or city
  • /O=MyCompany: Your organization
  • /OU=Clients: Organizational unit (e.g., Clients, Apps, etc.)
  • /CN=app-client-01: IMPORTANT: Unique client identifier

4.2 Sign the client certificate

# Sign the client certificate
openssl x509 -req -days 365 -sha256 \
  -in client/client.csr \
  -CA ca/certs/ca.crt \
  -CAkey ca/private/ca.key \
  -CAcreateserial \
  -out client/certs/client.crt \
  -extfile <(echo -e "basicConstraints=CA:FALSE\nkeyUsage=digitalSignature\nextendedKeyUsage=clientAuth")

# Verify the client certificate
openssl x509 -in client/certs/client.crt -text -noout

Enter fullscreen mode Exit fullscreen mode

Verificate client certificate

4.3 Create PKCS#12 file for the client

# Create PKCS#12 (p12/pfx) file for easy import
openssl pkcs12 -export \
  -inkey client/private/client.key \
  -in client/certs/client.crt \
  -certfile ca/certs/ca.crt \
  -out client/certs/client.p12

Enter fullscreen mode Exit fullscreen mode

Step 5: Deploy a "Hello World" with Docker Compose and mTLS

Let's create a simple example using Docker Compose with an Nginx server that responds "Hello World" and is protected with mTLS. Remember, this web app must be deployed using the same domain or IP used when generating the server keys in step 3.1.

5.1 Project structure

Create the following directory structure on your server:

mkdir -p ~/mtls-demo/nginx
cd ~/mtls-demo

Enter fullscreen mode Exit fullscreen mode

5.2 Copy the generated certificates

Copy the certificates we generated in the previous steps:

# Create certificate directory in the project
mkdir -p ~/mtls-demo/certs

# Copy server certificates (in our case they're on the same server)
cp ~/mtls-ca/server/certs/server-chain.crt ~/mtls-demo/certs/
cp ~/mtls-ca/server/private/server.key ~/mtls-demo/certs/

# Copy CA (for client verification)
cp ~/mtls-ca/ca/certs/ca.crt ~/mtls-demo/certs/

Enter fullscreen mode Exit fullscreen mode

5.3 Create the HTML page

Create the file ~/mtls-demo/nginx/index.html:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>mTLS - Hello World</title>
    <style>
        body {
            font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
            display: flex;
            justify-content: center;
            align-items: center;
            height: 100vh;
            margin: 0;
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: white;
        }
        .container {
            text-align: center;
            background: rgba(255, 255, 255, 0.1);
            padding: 3rem;
            border-radius: 20px;
            backdrop-filter: blur(10px);
            box-shadow: 0 8px 32px rgba(0, 0, 0, 0.1);
        }
        h1 { font-size: 3rem; margin-bottom: 0.5rem; }
        .cert-info {
            background: rgba(255, 255, 255, 0.15);
            padding: 1rem;
            border-radius: 10px;
            margin-top: 1.5rem;
            font-size: 0.9rem;
        }
        .badge {
            display: inline-block;
            background: #4CAF50;
            color: white;
            padding: 0.3rem 1rem;
            border-radius: 20px;
            font-size: 0.8rem;
            margin-top: 1rem;
        }
    </style>
</head>
<body>
    <div class="container">
        <h1>🔒 Hello World!</h1>
        <p>Secure connection established via <strong>mTLS</strong></p>
        <div class="cert-info">
            <p><strong>Authenticated client:</strong> <span id="client-cn">---</span></p>
            <p><strong>Protocol:</strong> TLS 1.3</p>
        </div>
        <div class="badge">✅ mTLS Enabled</div>
    </div>
</body>
</html>

Enter fullscreen mode Exit fullscreen mode

5.4 Configure Nginx with mTLS

Create the file ~/mtls-demo/nginx/default.conf:

server {
    listen 8443 ssl;
    server_name localhost;

    # Server certificates
    ssl_certificate /etc/nginx/certs/server-chain.crt;
    ssl_certificate_key /etc/nginx/certs/server.key;

    # Modern SSL configuration
    ssl_protocols TLSv1.2 TLSv1.3;
    ssl_ciphers HIGH:!aNULL:!MD5;
    ssl_prefer_server_ciphers off;
    ssl_session_cache shared:SSL:10m;
    ssl_session_timeout 10m;

    # mTLS: verify client
    ssl_client_certificate /etc/nginx/certs/ca.crt;
    ssl_verify_client on;
    ssl_verify_depth 2;

    # Document root
    root /usr/share/nginx/html;
    index index.html;

    location / {
        # Reject if client certificate is not valid
        if ($ssl_client_verify != SUCCESS) {
            return 403 "Access denied: client certificate required\n";
        }

        # Pass client information to the app
        add_header X-Client-CN $ssl_client_s_dn always;
        add_header X-Client-Verify $ssl_client_verify always;

        try_files $uri $uri/ =404;
    }

}

Enter fullscreen mode Exit fullscreen mode

5.5 Create the Docker Compose file

Create the file ~/mtls-demo/docker-compose.yml:

version: '3.8'

services:
  mtls-server:
    image: nginx:alpine
    container_name: mtls-nginx
    ports:
      - "8443:8443"
    volumes:
      - ./nginx/default.conf:/etc/nginx/conf.d/default.conf:ro
      - ./nginx/index.html:/usr/share/nginx/html/index.html:ro
      - ./certs/server-chain.crt:/etc/nginx/certs/server-chain.crt:ro
      - ./certs/server.key:/etc/nginx/certs/server.key:ro
      - ./certs/ca.crt:/etc/nginx/certs/ca.crt:ro
    restart: unless-stopped

Enter fullscreen mode Exit fullscreen mode

Structure website

5.6 Deploy the service

cd ~/mtls-demo

# Start the container
docker compose up -d

# Verify it's running
docker compose ps

# View logs
docker compose logs -f

# Stop the container
docker compose down

Enter fullscreen mode Exit fullscreen mode

5.7 Verify the deployment

Go to your browser and navigate to https://YOUR_WEB_IP_OR_DOMAIN:8443. You should see a 400 error since we haven't configured the browser to send the client certificate yet.

Website no tls

If we test with curl, we'll get a similar result:

Curl no tls

Step 6: Successful Tests

6.1 CURL with client certificate

curl -v \
  --cacert ca.crt \
  --cert client.crt \
  --key client.key \
  https://YOUR_WEB_IP_OR_DOMAIN:8443/

Enter fullscreen mode Exit fullscreen mode

You need to save these files in the path where you'll run the curl command. You can get them from the following server paths:

  • ca.crt => ~/mtls-ca/ca/certs/ca.crt
  • client.crt => ~/mtls-ca/client/certs/client.crt
  • client.key => ~/mtls-ca/client/private/client.key

Curl yes tls

6.2 Chrome with client certificate

Chrome and other browsers can use client certificates for mTLS authentication. To test this, you first need to import the .p12 certificate at the operating system level, since Chrome no longer allows importing them directly from its settings.

Download the certificate from the server:

scp root@server_ip:/root/mtls-ca/client/certs/client.p12 ./client.p12

Enter fullscreen mode Exit fullscreen mode

Import according to your operating system:

On macOS (Keychain Access):

open client.p12

Enter fullscreen mode Exit fullscreen mode

Keychain Access will open. Enter the password you set when creating the PKCS#12 file, and the certificate will be available for Chrome.

On Windows (Certificate Manager):

certmgr.msc

Enter fullscreen mode Exit fullscreen mode

  1. Go to "Personal""Certificates"
  2. Right-click → "All Tasks""Import..."
  3. Select client.p12 and enter the password

On Linux:

# Convert .p12 to .pem
openssl pkcs12 -in client.p12 -out client.pem -nodes

# Start Chrome with system certificate support
google-chrome --enable-features=PlatformCertificateProvider

Enter fullscreen mode Exit fullscreen mode

Firefox import p12

You might get an error initially, so it's best to test in an incognito tab or restart the browser so it picks up the newly installed certificate.

Firefox yes tls

Conclusion

Implementing mTLS is one of the best security investments you can make to protect communications between services. With this practical Docker Compose example, you've seen how to:

  1. Create a private CA and generate certificates
  2. Configure Nginx with mTLS in a Docker container
  3. Test with curl with and without a certificate
  4. Test with Chrome by importing the client certificate

This same pattern applies to production environments, Kubernetes microservices, internal APIs, and any communication requiring mutual authentication.

Additional Resources


Did you enjoy this tutorial? Share your experiences implementing mTLS or ask questions in the comments. What other security topics would you like to see in future articles?


Need a server for testing? You can create a Droplet on DigitalOcean using this link and get additional credit: https://m.do.co/c/2c579acd7121