Skip to content

Latest commit

 

History

History

Folders and files

NameName
Last commit message
Last commit date

parent directory

..
 
 
 
 
 
 

README.md

Node.js mTLS Client Example

A simple HTTPS client with mutual TLS authentication using Node.js built-in modules.

Features

  • ✅ Mutual TLS authentication
  • ✅ Server certificate verification
  • ✅ Multiple endpoint tests
  • ✅ No external dependencies
  • ✅ Pretty printed JSON output

Prerequisites

  • Node.js 14+ (built-in https module)
  • Certificates generated by the mtls CLI tool
  • Running mTLS server (Node.js, Go, or Caddy)

Setup

# Install dependencies (no runtime dependencies needed)
npm install

# Or use yarn
yarn install

Running the Client

# Using npm
npm start

# Or directly with node
node client.js

What It Tests

The client tests 4 endpoints:

  1. GET / - Main endpoint, displays client certificate info
  2. GET /health - Health check endpoint
  3. GET /api/data - Fetches sample data with metadata
  4. POST /api/echo - Sends JSON and receives echo response

Certificate Loading

The client loads:

  • Client certificate: Used to authenticate to the server
  • Client private key: Used for TLS handshake
  • CA certificate: Used to verify the server's certificate
const options = {
  key: fs.readFileSync('server-key.pem'),
  cert: fs.readFileSync('server-cert.pem'),
  ca: fs.readFileSync('ca-cert.pem'),
  rejectUnauthorized: true        // Verify server certificate
};

Configuration

You can modify the server URL in client.js:

const SERVER_URL = 'localhost';
const SERVER_PORT = 8443;

Example Output

🔒 mTLS Node.js Client
======================

📡 Test 1: Main endpoint (GET /)
✅ Status: 200
   Message: mTLS Node.js Server
   Client Certificate: localhost
   Verified: true
   Server Time: 2024-01-15T10:30:00.000Z

📡 Test 2: Health check (GET /health)
✅ Status: 200
   Response: OK

📡 Test 3: API data (GET /api/data)
✅ Status: 200
   Data:
   {
     "timestamp": "2024-01-15T10:30:00.000Z",
     "client": { ... },
     "server": { ... }
   }

📡 Test 4: Echo test (POST /api/echo)
✅ Status: 200
   Response: { ... }

✅ All tests completed successfully!

Troubleshooting

Connection refused:

  • Make sure the server is running on the correct port
  • Check if certificates are in the correct location

Certificate verification failed:

  • Ensure all certificates are signed by the same CA
  • Check certificate expiration dates
  • Verify CA certificate is loaded correctly

EPROTO error:

  • Server might not support the TLS version
  • Certificate might be corrupted or in wrong format