Securing FastAPI mTLS with Self-Signed Certificates
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.
Prerequisites
- Python 3.8+
- FastAPI (A modern, fast web framework for Python)
- OpenSSL (For generating self-signed certificates)
- HTTPS (For creating the client)
- 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