Laravel Sanctum Authentication with RSA-Encrypted Login Passwords

Laravel Sanctum Authentication with RSA-Encrypted Login Passwords

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

Frontend └── Encrypt password using RSA Public Key Backend ├── Decrypt password using RSA Private Key ├── Authenticate user └── Sanctum issues API token

✅ 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

composer create-project laravel/laravel laravel-sanctum-auth cd laravel-sanctum-auth

2️⃣ Install API Scaffolding

php artisan install:api

✔ Enables API middleware and prepares Sanctum for token authentication.

3️⃣ Configure Database

Edit .env:

DB_DATABASE=sanctum_api DB_USERNAME=root DB_PASSWORD=

Run migrations:

php artisan migrate

4️⃣ Install Laravel Sanctum

composer require laravel/sanctum php artisan vendor:publish --provider="Laravel\Sanctum\SanctumServiceProvider" php artisan migrate

Sanctum is now ready to issue API tokens.

5️⃣ Generate RSA Keys for Login Encryption

These keys are only used to encrypt login passwords.

mkdir -p storage/rsa

Generate Private Key

openssl genrsa -out storage/rsa/private.pem 2048

Generate Public Key

openssl rsa -in storage/rsa/private.pem -pubout -out storage/rsa/public.pem

📁 RSA Key Structure

storage/rsa/ ├── private.pem 🔐 Keep secret (DO NOT COMMIT) └── public.pem 🔓 Safe to share with frontend

6️⃣ Configure API Guard (Sanctum)

Edit config/auth.php:

'guards' => [ 'api' => [ 'driver' => 'sanctum', 'provider' => 'users', ], ],

7️⃣ Update User Model

Edit app/Models/User.php:

use Laravel\Sanctum\HasApiTokens; class User extends Authenticatable { use HasApiTokens, Notifiable; protected $fillable = [ 'name', 'email', 'password', ]; protected $hidden = [ 'password', 'remember_token', ]; }

8️⃣ Create Authentication Controller

php artisan make:controller Api/AuthController

app/Http/Controllers/Api/AuthController.php

<?php namespace App\Http\Controllers\Api; use App\Http\Controllers\Controller; use App\Models\User; use Illuminate\Http\Request; use Illuminate\Support\Facades\Auth; use Illuminate\Support\Facades\Hash; class AuthController extends Controller { private string $privateKey; public function __construct() { $this->privateKey = file_get_contents(storage_path('rsa/private.pem')); if (!$this->privateKey) { throw new \Exception('RSA private key not found'); } } // Register user public function register(Request $request) { $data = $request->validate([ 'name' => 'required|string|max:255', 'email' => 'required|email|unique:users', 'password' => 'required|string|min:6|confirmed', ]); User::create([ 'name' => $data['name'], 'email' => $data['email'], 'password' => Hash::make($data['password']), ]); return response()->json(['message' => 'User registered successfully'], 201); } // Login with RSA-encrypted password public function login(Request $request) { $request->validate([ 'email' => 'required|email', 'password' => 'required|string', ]); $encryptedPassword = base64_decode($request->password); $decryptedPassword = null; if (!openssl_private_decrypt( $encryptedPassword, $decryptedPassword, $this->privateKey )) { return response()->json(['message' => 'Password decryption failed'], 400); } if (!Auth::attempt([ 'email' => $request->email, 'password' => $decryptedPassword, ])) { return response()->json(['message' => 'Invalid credentials'], 401); } $user = Auth::user(); $token = $user->createToken('api-token')->plainTextToken; return response()->json([ 'user' => $user, 'access_token' => $token, 'token_type' => 'Bearer', ]); } // Get authenticated profile public function profile(Request $request) { return response()->json($request->user()); } // Logout user public function logout(Request $request) { $request->user()->currentAccessToken()->delete(); return response()->json(['message' => 'Logged out successfully']); } }

9️⃣ Define API Routes

Edit routes/api.php:

use App\Http\Controllers\Api\AuthController; Route::prefix('auth')->group(function () { Route::post('/register', [AuthController::class, 'register']); Route::post('/login', [AuthController::class, 'login']); Route::middleware('auth:sanctum')->group(function () { Route::get('/profile', [AuthController::class, 'profile']); Route::post('/logout', [AuthController::class, 'logout']); }); });

▶️ Run the Application

php artisan serve

Base URL:

http://localhost:8000

🚀 API Testing with Postman

1️⃣ Register User

POST /api/auth/register { "name": "StarCode Kh", "email": "starcodekh@example.com", "password": "12345678", "password_confirmation": "12345678" }

2️⃣ Login (RSA Encrypted)

POST /api/auth/login { "email": "starcodekh@example.com", "password": "ENCRYPTED_PASSWORD_BASE64" }

📌 Encrypt password using storage/rsa/public.pem

3️⃣ Get Profile

GET /api/auth/profile Authorization: Bearer {access_token}

4️⃣ Logout

POST /api/auth/logout Authorization: Bearer {access_token}

🔁 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.

Souy Soeng

Souy Soeng

Hi there 👋, I’m Soeng Souy (StarCode Kh)
-------------------------------------------
🌱 I’m currently creating a sample Laravel and React Vue Livewire
👯 I’m looking to collaborate on open-source PHP & JavaScript projects
💬 Ask me about Laravel, MySQL, or Flutter
⚡ Fun fact: I love turning ☕️ into code!

Post a Comment

CAN FEEDBACK
close