In this guide, I’ll show you how to enhance your Laravel authentication system by adding a secure, face-based login feature using Python's powerful face recognition library. Face recognition adds an extra layer of security to your application and provides users with a seamless, contactless login experience.
We’ll combine the strengths of Laravel and Python for a practical, biometric security solution, making authentication more robust and user-friendly.
Let’s walk through the steps, from setting up Python and Laravel integration to creating the face recognition logic and adding it to the Laravel login system.
You’ll see example code and practical guidance to implement this in your Laravel project.
Laravel Authentication with Python Face Recognition
First, install Python and the face recognition library. The face_recognition library depends on dlib
, so make sure your environment supports it:
# Install face_recognition with dlib support
pip install face_recognition
Note: You may also need to install cmake
and dlib
manually, depending on your OS.
To enable Laravel and Python to communicate, we’ll use the Laravel HTTP client to send images to a Python API for face verification.
Install Flask:
pip install Flask
Create a Python file, face_auth_api.py, that will process the face recognition.
from flask import Flask, request, jsonify
import face_recognition
import base64
import io
from PIL import Image
app = Flask(__name__)
@app.route('/verify-face', methods=['POST'])
def verify_face():
# Load reference image (stored in server or database)
reference_image_path = "reference_image.jpg"
reference_image = face_recognition.load_image_file(reference_image_path)
reference_encoding = face_recognition.face_encodings(reference_image)[0]
# Decode the uploaded image
data = request.json['image']
img_data = base64.b64decode(data)
uploaded_image = Image.open(io.BytesIO(img_data))
uploaded_image_np = face_recognition.load_image_file(uploaded_image)
# Get encodings for the uploaded image
uploaded_encodings = face_recognition.face_encodings(uploaded_image_np)
if uploaded_encodings:
uploaded_encoding = uploaded_encodings[0]
# Compare faces
match = face_recognition.compare_faces([reference_encoding], uploaded_encoding)
return jsonify({"match": match[0]})
else:
return jsonify({"error": "No face detected"}), 400
if __name__ == '__main__':
app.run(host="0.0.0.0", port=5000)
In this script, we load a reference image of the user (stored on the server), compare it with the uploaded image, and return the match result.
In your Laravel project, create a controller to handle the image submission and process the response from the Python API.
Install Laravel HTTP client if not installed:
composer require guzzlehttp/guzzle
Create a Controller for Face Authentication:
php artisan make:controller FaceAuthController
In FaceAuthController.php, add the following code to handle the face verification:
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Http;
class FaceAuthController extends Controller
{
public function verifyFace(Request $request)
{
// Convert image to Base64 format
$image = $request->file('face_image');
$imageData = base64_encode(file_get_contents($image));
// Send image to Python API for verification
$response = Http::post('http://localhost:5000/verify-face', [
'image' => $imageData,
]);
$result = $response->json();
if (isset($result['match']) && $result['match']) {
return response()->json(['success' => 'Face verified successfully!']);
}
return response()->json(['error' => 'Face verification failed!'], 401);
}
}
In your web.php or api.php routes file, add a route for face authentication:
use App\Http\Controllers\FaceAuthController;
Route::post('/face-auth', [FaceAuthController::class, 'verifyFace']);
To test the face verification, create a simple form where users can upload their image for face-based login.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Face Authentication</title>
</head>
<body>
<h2>Login with Face Recognition</h2>
<form action="/face-auth" method="POST" enctype="multipart/form-data">
@csrf
<label for="face_image">Upload Face Image:</label>
<input type="file" id="face_image" name="face_image" required>
<button type="submit">Verify Face</button>
</form>
</body>
</html>
Start the Python API server:
python face_auth_api.py
Start your Laravel application, navigate to the form, and upload an image to test the face authentication.
In LoginController.php, modify the login logic to include face verification before allowing access.
public function login(Request $request)
{
// Normal login logic here...
// Call the face verification method
$faceAuthController = new FaceAuthController();
$faceAuthResponse = $faceAuthController->verifyFace($request);
if ($faceAuthResponse->status() === 401) {
return redirect()->back()->withErrors(['face_auth' => 'Face verification failed.']);
}
// If face verification is successful, proceed with login
return redirect()->intended('dashboard');
}
You might also like:
In this article, we will see a stripe payment gateway integration example in laravel 8. The stripe payment gateway...
Nov-26-2020
In this article, we will see how to send bulk mail using queue in laravel 9. Laravel queue is used for sending bulk...
Mar-15-2022
In this article, we will see laravel 9 whereColumn() query example. The whereCoulmn method is used to verify whethe...
Oct-21-2022
In this tutorial, we will see how to disable past dates in jquery datepicker. In the date picker, today's date...
Jun-18-2022