We use JWT (JSON Web Tokens) for stateless authentication and RSA encryption to encrypt passwords on the client before sending them to the backend. On the server, passwords are decrypted using a private RSA key and verified using bcrypt, backed by a MySQL database.
📌 Tech Stack
-
Python 3.10+
-
FastAPI
-
MySQL
-
JWT (
python-jose) -
RSA Encryption (Public / Private Key)
-
bcrypt
-
Postman
🧠 Authentication Flow
-
Client encrypts password using RSA Public Key
-
Server decrypts password using RSA Private Key
-
Password verified using bcrypt
-
JWT token issued
-
Protected routes secured with JWT dependency
📦 Requirements
-
Python 3.10+
-
MySQL 8+
-
OpenSSL
-
Postman
1️⃣ Create Python Project
2️⃣ Install Dependencies
3️⃣ Create Project Folder Structure
Folder Purpose
| Folder | Description |
|---|---|
| app/api | API endpoints |
| app/middleware | JWT auth middleware |
| app/utils | JWT & RSA helpers |
| app/db | Database connection |
| storage/rsa | RSA key storage |
4️⃣ Create Required Files
5️⃣ Configure .gitignore
⚠️ Never commit your private RSA key.
6️⃣ Environment Variables (.env)
7️⃣ MySQL Database Setup
8️⃣ Generate RSA Keys (OpenSSL)
-
public.pem→ frontend encryption -
private.pem→ backend decryption
9️⃣ MySQL Connection
app/db/mysql.py
🔟 JWT Helper
app/utils/jwt.py
1️⃣1️⃣ RSA Helper
app/utils/rsa.py
1️⃣2️⃣ Register API
app/api/auth/register.py
1️⃣3️⃣ Login API
app/api/auth/login.py
1️⃣4️⃣ JWT Middleware
app/middleware/auth.py
1️⃣5️⃣ Profile API
app/api/auth/profile.py
1️⃣6️⃣ Logout API
app/api/auth/logout.py
1️⃣7️⃣ Main App
app/main.py
▶️ Run Application
Base URL:
🚀 Postman Testing
✅ Register
POST /register
🔐 Encrypt Password (Client)
Use public.pem to encrypt password before login.
Encrypted output → Base64
✅ Login
POST /login
🔒 Profile (Protected)
GET /profile
Header
🚪 Logout
POST /logout
Header
✅ Production Best Practices
-
Use HTTPS
-
Never commit
private.pem -
Rotate RSA keys
-
Short-lived JWT tokens
-
Rate-limit login attempts
-
Secure
.envfiles
🎯 Final Result
You now have a clean, professional, production-ready Python authentication REST API using:
🔐 RSA-encrypted passwords
🔑 JWT authentication
🛡 MySQL backend
🔗 Source Code
Want the full source code?
👉 Download the complete Python JWT Authentication with RSA example from my GitHub repository

