Securing FastAPI mTLS with Self-Signed Certificates

Abhishek koserwal
4 min readOct 1, 2024

Securing APIs is crucial in today’s digital world, especially when handling sensitive data. One effective method is mutual TLS (mTLS), which authenticates the client and the server using certificates. This blog will demonstrate how to secure a FastAPI application and a Python client using mTLS with self-signed certificates.

mTLS flow between FastAPI and Python client

Prerequisites

  1. Python 3.8+
  2. FastAPI (A modern, fast web framework for Python)
  3. OpenSSL (For generating self-signed certificates)
  4. HTTPS (For creating the client)
  5. Uvicorn (ASGI server for FastAPI)

Code Repository

git clone https://github.com/akoserwal/fastapi-patterns
cd fastapi-mTLS/

Step 1: Generate Self-Signed Certificates

We’ll use OpenSSL to create self-signed certificates for the server and the client, which will authenticate both parties. For a detailed blog on generating certificates, see Create Your Own CA and Sign Server & Client Certificates for local development.

Self-signed Certificates localhost are present in the folder.

fastapi-patterns/fastapi-mTLS/tls-certs

--

--

Abhishek koserwal
Abhishek koserwal

Written by Abhishek koserwal

#redhatter #opensource #developer #kubernetes #keycloak #golang #openshift #quarkus #spring