This tutorial demonstrates how to build a secure API authentication system in Laravel using Laravel Sanctum, enhanced with RSA encryption for login passwords.
⚠️ Laravel Sanctum already provides secure token authentication.
In this guide, we add RSA encryption to protect user passwords before they reach the backend, adding an extra layer of security.
🧠 How It Works
Authentication Flow
✅ What This Tutorial Covers
-
Laravel Sanctum API authentication
-
RSA public / private key encryption
-
Secure Register, Login, Profile, Logout APIs
-
RSA-encrypted login passwords
-
Token-based protected routes
-
Production-ready best practices
📦 Requirements
-
PHP 8.1+
-
Laravel 10 / 11 / 12
-
Composer
-
OpenSSL enabled
-
Postman (for testing)
-
Basic Laravel knowledge
1️⃣ Create a New Laravel Project
2️⃣ Install API Scaffolding
✔ Enables API middleware and prepares Sanctum for token authentication.
3️⃣ Configure Database
Edit .env:
Run migrations:
4️⃣ Install Laravel Sanctum
Sanctum is now ready to issue API tokens.
5️⃣ Generate RSA Keys for Login Encryption
These keys are only used to encrypt login passwords.
Generate Private Key
Generate Public Key
📁 RSA Key Structure
6️⃣ Configure API Guard (Sanctum)
Edit config/auth.php:
7️⃣ Update User Model
Edit app/Models/User.php:
8️⃣ Create Authentication Controller
app/Http/Controllers/Api/AuthController.php
9️⃣ Define API Routes
Edit routes/api.php:
▶️ Run the Application
Base URL:
🚀 API Testing with Postman
1️⃣ Register User
2️⃣ Login (RSA Encrypted)
📌 Encrypt password using storage/rsa/public.pem
3️⃣ Get Profile
4️⃣ Logout
🔁 Authentication Flow Summary
-
Register → Password hashed
-
Login → Password encrypted using RSA public key
-
Backend → Decrypt password using private key
-
Sanctum → Issues API token
-
Protected routes → Bearer token
-
Logout → Token revoked
✅ Production Best Practices
-
Always use HTTPS
-
Never commit RSA private keys
-
Protect
storage/rsa/private.pem -
Use short-lived tokens
-
Rate-limit login requests
-
Rotate RSA keys periodically
🎯 Final Result
You now have a secure, modern, production-ready API authentication system using:
🔐 RSA-encrypted login passwords
🔑 Laravel Sanctum
🛡 Token-based API security
Want the full source code?
Download the complete Laravel Sanctum Authentication with RSA example on my GitHub repo here.

