A secure, full-stack biometric authentication system featuring facial recognition and voice verification for two-factor authentication. Built with modern web technologies and machine learning models for robust identity verification.
- Secure Authentication: Implement multi-modal biometric verification combining face and voice recognition
- User-Friendly: Provide an intuitive web interface for enrollment and login
- Scalable: Use vector databases (pgvector) for efficient similarity searches
- Production-Ready: Containerized deployment with Docker for easy setup
- Privacy-Focused: Process biometrics locally without external API dependencies
- FastAPI: High-performance async web framework for Python
- PostgreSQL + pgvector: Vector database for storing and querying biometric embeddings
- DeepFace: Facial recognition using Facenet512 model
- SpeechBrain: Speaker verification with ECAPA-TDNN model
- SQLAlchemy: ORM for database operations
- PassLib: Secure password hashing
- React: Component-based UI library
- Vite: Fast build tool and development server
- Axios: HTTP client for API communication
- Framer Motion: Smooth animations and transitions
- Docker & Docker Compose: Containerized deployment
- JWT: Token-based authentication
- WebRTC: Real-time camera and microphone access
- Docker and Docker Compose installed
- At least 4GB RAM available
-
Clone the repository
git clone https://github.com/AYOUBnsr/biometric-auth.git cd biometric-auth -
Start the services
docker-compose up --build
-
Access the application
- Frontend: http://localhost:5173
- Backend API: http://localhost:8000
- API Documentation: http://localhost:8000/docs
The first run will download ML models (~400MB), which may take a few minutes.
- Python 3.8+
- Node.js 16+
- PostgreSQL 12+ with pgvector extension
- System dependencies (varies by OS)
Using Docker (easiest):
docker run --name postgres-biometric -e POSTGRES_DB=biometric_auth -e POSTGRES_USER=biometric -e POSTGRES_PASSWORD=biometric_pass -p 5432:5432 -d pgvector/pgvector:pg15Manual PostgreSQL setup:
CREATE USER biometric WITH PASSWORD 'biometric_pass';
CREATE DATABASE biometric_auth OWNER biometric;
GRANT ALL PRIVILEGES ON DATABASE biometric_auth TO biometric;
\\c biometric_auth
CREATE EXTENSION IF NOT EXISTS vector;cd backend
# Create virtual environment
python -m venv .venv
source .venv/bin/activate # On Windows: .venv\Scripts\activate
# Install dependencies
pip install -r requirements.txt
# Configure environment
cp .env.example .env
# Edit .env with your database URL and secret key
# Run the server
uvicorn main:app --reload --port 8000cd frontend
# Install dependencies
npm install
# Start development server
npm run dev- Navigate to the registration page
- Enter username, email, and password
- Capture 4 face frames by positioning your face in the circle
- Record a voice sample by speaking the passphrase clearly
- Complete registration
- Enter your username
- Scan your face for initial verification
- Speak the passphrase for voice verification
- Access granted with JWT token
POST /auth/register- User registration with biometricsPOST /auth/login/face- Face verification (returns session token)POST /auth/login/voice- Voice verification (returns JWT)GET /auth/me- Get user profile (requires JWT)POST /auth/logout- Logout and revoke token
# Database
DATABASE_URL=postgresql+asyncpg://biometric:biometric_pass@localhost:5432/biometric_auth
# Security
SECRET_KEY=your-very-long-random-secret-key-here-change-in-production
ALGORITHM=HS256
ACCESS_TOKEN_EXPIRE_MINUTES=60
# Thresholds
FACE_SIMILARITY_THRESHOLD=0.40
VOICE_SIMILARITY_THRESHOLD=0.70
ENABLE_LIVENESS_DETECTION=false
# Frontend
FRONTEND_URL=http://localhost:5173
# ML Models
SPEECHBRAIN_MODEL=speechbrain/spkrec-ecapa-voxceleb- Face: Lower values (e.g., 0.30) are more permissive but less secure
- Voice: Adjust based on your microphone quality and environment noise
βββββββββββββββββββ βββββββββββββββββββ
β React App β β FastAPI β
β (Frontend) βββββΊβ (Backend) β
β β β β
β - Face Scanner β β - Auth Router β
β - Voice Recorderβ β - ML Models β
β - Dashboard β β - JWT Tokens β
βββββββββββββββββββ βββββββββββββββββββ
β β
βΌ βΌ
βββββββββββββββββββ βββββββββββββββββββ
β PostgreSQL + β β ML Models β
β pgvector β β β
β β β - DeepFace β
β - User data β β - SpeechBrain β
β - Embeddings β β β
βββββββββββββββββββ βββββββββββββββββββ
This project is licensed under the MIT License - see the LICENSE file for details.
- Change default passwords and secret keys in production
- Use HTTPS in production
- Regularly update ML model dependencies
- Monitor for adversarial attacks on biometric systems
- Consider additional liveness detection for high-security applications
If you encounter issues:
- Check the API documentation at
/docs - Verify your environment matches the prerequisites
- Ensure camera and microphone permissions are granted
- Check logs for detailed error messages
Built with β€οΈ using modern web technologies and machine learning.
Create backend/.env from backend/.env.example:
# Database
DATABASE_URL=postgresql+asyncpg://biometric:biometric_pass@localhost:5432/biometric_auth
# JWT β generate with: python -c "import secrets; print(secrets.token_hex(32))"
SECRET_KEY=your-very-long-random-secret-key-here
ALGORITHM=HS256
ACCESS_TOKEN_EXPIRE_MINUTES=60
# Biometric thresholds (0.0 β 1.0)
FACE_SIMILARITY_THRESHOLD=0.40
VOICE_SIMILARITY_THRESHOLD=0.75
# Liveness detection (basic heuristic, not production-grade)
ENABLE_LIVENESS_DETECTION=false
# CORS
FRONTEND_URL=http://localhost:5173
# SpeechBrain model
SPEECHBRAIN_MODEL=speechbrain/spkrec-ecapa-voxceleb# Build and start all services
docker-compose up --build
# Frontend: http://localhost:5173
# Backend: http://localhost:8000
# API docs: http://localhost:8000/docs| Method | Endpoint | Auth | Description |
|---|---|---|---|
| POST | /auth/register |
None | Register user with face + voice + password |
| POST | /auth/login/face |
None | Step 1: face scan β session_token |
| POST | /auth/login/voice |
None | Step 2: voice + session_token β JWT |
| GET | /auth/me |
Bearer JWT | Get current user profile |
| POST | /auth/logout |
Bearer JWT | Revoke JWT |
| GET | /health |
None | Health check |
username string
email string
password string
face_frames file[] (2β5 JPEG/PNG images)
voice_sample file (WAV or WebM, β₯ 4 seconds)
username string
face_frame file (single JPEG/PNG)
session_token string (from /login/face)
voice_sample file (WAV or WebM, β₯ 3 seconds)
-- Users with biometric embeddings
CREATE TABLE users (
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
username VARCHAR(64) UNIQUE NOT NULL,
email VARCHAR(255) UNIQUE NOT NULL,
hashed_password VARCHAR(255) NOT NULL,
face_embedding VECTOR(512), -- Facenet512
voice_embedding VECTOR(192), -- ECAPA-TDNN
is_active BOOLEAN DEFAULT true,
biometric_registered BOOLEAN DEFAULT false,
created_at TIMESTAMPTZ DEFAULT NOW(),
updated_at TIMESTAMPTZ DEFAULT NOW()
);
-- Two-step login state (face verified β waiting for voice)
CREATE TABLE pending_sessions (
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
session_token VARCHAR(256) UNIQUE NOT NULL,
user_id UUID NOT NULL,
face_confidence FLOAT,
face_verified BOOLEAN DEFAULT false,
created_at TIMESTAMPTZ DEFAULT NOW(),
expires_at TIMESTAMPTZ NOT NULL, -- 5 min TTL
used BOOLEAN DEFAULT false
);
-- JWT blacklist for logout
CREATE TABLE revoked_tokens (
id SERIAL PRIMARY KEY,
jti VARCHAR(256) UNIQUE NOT NULL,
revoked_at TIMESTAMPTZ DEFAULT NOW(),
expires_at TIMESTAMPTZ NOT NULL,
reason TEXT
);cd backend
# Auto-generate migration after model changes
alembic revision --autogenerate -m "describe change"
# Apply migrations
alembic upgrade head
# Rollback one step
alembic downgrade -1speechbrain==1.0.0requirestorch>=2.0. Therequirements.txtpinstorch==2.2.2.- On Arch Linux, install torch from PyPI (not
python-pytorchfrom pacman) to avoid CUDA/ABI conflicts:pip install torch==2.2.2 torchaudio==2.2.2 --index-url https://download.pytorch.org/whl/cpu
- The ECAPA model downloads ~400 MB on first use from HuggingFace Hub. Set
HF_HUB_OFFLINE=1after the first download.
- DeepFace pulls
tensorflowas a dependency. On Arch,tf-kerasmust be installed separately (included inrequirements.txt). - If you see
No module named 'keras', run:pip install tf-keras - For GPU acceleration: install
tensorflow-gpuinstead oftensorflow.
- The
pgvectorextension must be installed in PostgreSQL before running the app. - Vector dimension must match what the model outputs. Facenet512 β 512-d, ECAPA-TDNN β 192-d.
- If you change models, drop and recreate the
userstable or write a migration to change vector dimensions.
- The frontend records in
audio/webm;codecs=opus(Chrome/Firefox default). - The backend uses
librosaas a fallback decoder for WebM β float32 PCM. - If
librosafails to decode, installffmpegsystem-wide:sudo pacman -S ffmpeg.
- Default threshold
0.40(cosine similarity) works well for Facenet512 under decent lighting. - Lower values = stricter (fewer false positives). Higher = more lenient.
- Tune via
FACE_SIMILARITY_THRESHOLDenv var without code changes.
- The current liveness check is a basic heuristic (pixel variance across frames).
- For production, use a dedicated model like
Silent-Face-Anti-Spoofingor a commercial SDK. - Enable with
ENABLE_LIVENESS_DETECTION=trueβ disabled by default..
- Webcam and microphone APIs require HTTPS in production (browser security policy).
- Use
nginx+ Let's Encrypt, or a reverse proxy like Caddy:sudo pacman -S caddy # Caddyfile: yourdomain.com { reverse_proxy localhost:8000 }
biometric-auth/
βββ backend/
β βββ main.py # FastAPI app entry point
β βββ app_config.py # Pydantic settings
β βββ database.py # SQLAlchemy async engine + init_db
β βββ models.py # ORM models (User, PendingSession, RevokedToken)
β βββ schemas.py # Pydantic request/response schemas
β βββ auth/
β β βββ face.py # DeepFace embedding extraction + comparison
β β βββ voice.py # SpeechBrain ECAPA embedding + comparison
β β βββ jwt.py # Token creation, validation, revocation
β βββ routers/
β β βββ auth.py # All /auth/* endpoints
β βββ alembic/ # Database migrations
β βββ requirements.txt
β βββ .env.example
β βββ Dockerfile
βββ frontend/
β βββ src/
β β βββ App.jsx # Router + AuthContext
β β βββ main.jsx # React entry point
β β βββ index.css # Global dark theme styles
β β βββ api.js # Axios client + all API calls
β β βββ pages/
β β β βββ Register.jsx # 4-step registration wizard
β β β βββ Login.jsx # 2-step biometric login
β β β βββ Dashboard.jsx# Protected user dashboard
β β βββ components/
β β βββ FaceScanner.jsx # Webcam + animated scan UI
β β βββ VoiceRecorder.jsx # Web Audio API waveform visualizer
β β βββ StepIndicator.jsx # Animated step progress
β β βββ ConfidenceBar.jsx # Animated confidence score bar
β βββ index.html
β βββ vite.config.js
β βββ package.json
β βββ Dockerfile
βββ docker-compose.yml
βββ README.md
