📖 README Documentation

Complete documentation for the Laravel 2FA Authentication System

🔐 Laravel 2FA Authentication System

!Laravel

!PHP

!MySQL

!Tailwind CSS

A complete Two-Factor Authentication (2FA) system built with Laravel 12, featuring custom TOTP implementation, AES encryption, and a beautiful liquid glass UI.

🚀 Live Demo📖 Documentation🔧 Installation📋 Features

---

📋 Table of Contents

  • 🌟 Features
  • 🏗️ System Architecture
  • 📊 How It Works
  • 🚀 Installation
  • ⚙️ Configuration
  • 🔧 Usage
  • 📚 API Documentation
  • 🛠️ Development
  • 🔒 Security
  • 🤝 Contributing
  • 📄 License
  • ---

    🌟 Features

    🔐 Security Features

  • Custom TOTP Implementation - No third-party dependencies
  • AES-256-CBC Encryption - Secure secret storage
  • Time-based Validation - ±30 second window tolerance
  • Session Management - Secure 2FA verification flow
  • Rate Limiting - Protection against brute force attacks
  • 🎨 UI/UX Features

  • Liquid Glass Design - Modern, eye-friendly interface
  • Responsive Layout - Works on all devices
  • Loading States - Smooth user experience
  • Error Handling - Clear, helpful error messages
  • Copy-to-Clipboard - Easy credential sharing
  • 🔧 Technical Features

  • Laravel 12 - Latest framework version
  • MySQL Database - Reliable data storage
  • Custom Services - Modular, maintainable code
  • Development Tools - Debug routes and bypass options
  • Comprehensive Logging - Detailed debugging information
  • ---

    🏗️ System Architecture

    graph TB

    subgraph "Frontend Layer"

    A[Login Page] --> B[2FA Setup]

    B --> C[QR Code Display]

    C --> D[2FA Confirmation]

    D --> E[Dashboard]

    F[2FA Verification] --> E

    end

    subgraph "Backend Layer"

    G[WebAuthController] --> H[TOTPService]

    G --> I[CustomEncryptor]

    G --> J[QRCodeService]

    H --> K[Base32 Encoding]

    H --> L[HMAC-SHA1]

    I --> M[AES-256-CBC]

    end

    subgraph "Data Layer"

    N[MySQL Database] --> O[Users Table]

    O --> P[totp_secret_encrypted]

    O --> Q[is_2fa_enabled]

    end

    subgraph "External Services"

    R[Google Authenticator] --> S[QR Code Scanner]

    T[Authy] --> S

    U[Other TOTP Apps] --> S

    end

    A --> G

    B --> G

    C --> G

    D --> G

    F --> G

    G --> N

    S --> C

    ---

    📊 How It Works

    🔄 2FA Setup Flow

    sequenceDiagram

    participant U as User

    participant C as Controller

    participant T as TOTPService

    participant E as Encryptor

    participant D as Database

    U->>C: Access 2FA Setup

    C->>T: Generate Secret

    T->>C: Return Secret

    C->>C: Generate QR Code

    C->>U: Display QR + Secret

    U->>U: Scan QR Code

    U->>U: Generate TOTP Code

    U->>C: Submit TOTP Code

    C->>T: Validate TOTP

    T->>C: Validation Result

    C->>E: Encrypt Secret

    E->>C: Encrypted Secret

    C->>D: Save User 2FA Data

    C->>U: 2FA Enabled Success

    🔐 2FA Verification Flow

    sequenceDiagram

    participant U as User

    participant C as Controller

    participant T as TOTPService

    participant E as Encryptor

    participant D as Database

    U->>C: Login Request

    C->>D: Check User 2FA Status

    D->>C: User Has 2FA Enabled

    C->>U: Redirect to 2FA Verify

    U->>U: Generate TOTP Code

    U->>C: Submit TOTP Code

    C->>E: Decrypt Stored Secret

    E->>C: Decrypted Secret

    C->>T: Validate TOTP

    T->>C: Validation Result

    C->>U: Grant Access / Show Error

    🔧 TOTP Generation Process

    🔧 TOTP Generation Process

    Step 1: Get current Unix timestamp

    Step 2: Divide by 30 and round down (floor)

    Step 3: Convert to 8-byte big-endian format

    Step 4: Generate HMAC using secret key

    Step 5: Use last byte to determine offset

    Step 6: Extract 4-byte integer from offset

    Step 7: Take remainder when divided by 1,000,000

    Step 8: Pad to 6 digits if needed

    📝 Example:

    Time: 1640995200 (Jan 1, 2022 00:00:00 UTC)

    Time Step: 54699840

    Secret: JBSWY3DPEHPK3PXP

    Result: 6-digit TOTP code (e.g., 123456)

    ---

    🚀 Installation

    Prerequisites

  • PHP 8.1 or higher
  • Composer
  • MySQL 8.0 or higher
  • Node.js (for asset compilation)
  • Step 1: Clone the Repository

    git clone https://github.com/yourusername/laravel-2fa-system.git

    cd laravel-2fa-system

    Step 2: Install Dependencies

    composer install

    npm install

    Step 3: Environment Setup

    cp .env.example .env

    php artisan key:generate

    Step 4: Database Configuration

    DB_CONNECTION=mysql

    DB_HOST=127.0.0.1

    DB_PORT=3306

    DB_DATABASE=your_database_name

    DB_USERNAME=your_username

    DB_PASSWORD=your_password

    Step 5: Run Migrations

    php artisan migrate

    Step 6: Seed Demo Data

    php artisan db:seed

    Step 7: Compile Assets

    npm run build

    Step 8: Start the Server

    php artisan serve

    ---

    ⚙️ Configuration

    2FA Configuration (config/2fa.php)

    
    

    return [

    // Encryption Configuration

    'encryption_key' => env('2FA_ENCRYPTION_KEY', 'base64:your-32-byte-key'),

    'encryption_iv' => env('2FA_ENCRYPTION_IV', 'base64:your-16-byte-iv'),

    // TOTP Configuration

    'totp_digits' => env('2FA_TOTP_DIGITS', 6),

    'totp_period' => env('2FA_TOTP_PERIOD', 30),

    'totp_window' => env('2FA_TOTP_WINDOW', 1),

    // App Configuration

    'app_name' => env('2FA_APP_NAME', config('app.name')),

    // Cache Configuration

    'cache_prefix' => env('2FA_CACHE_PREFIX', '2fa_'),

    'cache_ttl' => env('2FA_CACHE_TTL', 300),

    ];

    Environment Variables

    2FA Configuration

    2FA_ENCRYPTION_KEY=base64:your-32-byte-encryption-key-here

    2FA_ENCRYPTION_IV=base64:your-16-byte-iv-here

    2FA_APP_NAME="Your App Name"

    2FA_TOTP_DIGITS=6

    2FA_TOTP_PERIOD=30

    2FA_TOTP_WINDOW=1

    Generate Encryption Keys

    Generate 32-byte encryption key

    php -r "echo '2FA_ENCRYPTION_KEY=base64:' . base64_encode(random_bytes(32)) . PHP_EOL;"

    Generate 16-byte IV

    php -r "echo '2FA_ENCRYPTION_IV=base64:' . base64_encode(random_bytes(16)) . PHP_EOL;"

    ---

    🔧 Usage

    Demo Credentials

    Email: test@example.com

    Password: password

    2FA Setup Process

  • Login to the application
  • Navigate to Dashboard → 2FA Settings
  • Click "Setup 2FA" button
  • Scan the QR code with your authenticator app:
  • - Google Authenticator

    - Authy

    - Microsoft Authenticator

    - Any TOTP-compatible app

  • Enter the 6-digit code from your app
  • Confirm setup
  • Development Bypass

    In development mode, you can use the bypass code 123456 to skip 2FA verification.

    API Endpoints

    Method | Endpoint | Description
    ------ | -------------- | ---------------------
    GET | /login | Show login form
    POST | /login | Handle login
    GET | /dashboard | User dashboard
    GET | /2fa/setup | 2FA setup page
    POST | /2fa/setup | Generate 2FA secret
    GET | /2fa/confirm | 2FA confirmation page
    POST | /2fa/confirm | Confirm 2FA setup
    GET | /2fa/verify | 2FA verification page
    POST | /2fa/verify | Verify 2FA code
    GET | /2fa/disable | 2FA disable page
    POST | /2fa/disable | Disable 2FA

    ---

    📚 API Documentation

    Authentication Flow

    // 1. Login

    POST /login

    {

    "email": "user@example.com",

    "password": "password"

    }

    // 2. Setup 2FA (if not enabled)

    POST /2fa/setup

    // Returns QR code and secret

    // 3. Confirm 2FA Setup

    POST /2fa/confirm

    {

    "code": "123456"

    }

    // 4. Verify 2FA (on subsequent logins)

    POST /2fa/verify

    {

    "code": "123456"

    }

    Response Formats

    {

    "success": true,

    "message": "2FA enabled successfully",

    "data": {

    "user_id": 1,

    "is_2fa_enabled": true

    }

    }

    ---

    🛠️ Development

    Project Structure

    authenticator-test-app/

    ├── app/

    │ ├── Http/Controllers/

    │ │ └── WebAuthController.php # Main authentication controller

    │ ├── CustomEncryptor.php # AES encryption service

    │ ├── TOTPService.php # TOTP generation/validation

    │ └── QRCodeService.php # QR code generation

    ├── config/

    │ └── 2fa.php # 2FA configuration

    ├── database/

    │ ├── migrations/

    │ │ └── create_users_table.php # User table with 2FA fields

    │ └── seeders/

    │ └── UserSeeder.php # Demo user seeder

    ├── resources/

    │ └── views/

    │ ├── auth/ # Authentication views

    │ ├── docs/ # Documentation views

    │ └── layouts/

    │ └── app.blade.php # Main layout

    └── routes/

    └── web.php # Web routes

    Development Commands

    Start development server

    php artisan serve

    Run tests

    php artisan test

    Clear cache

    php artisan cache:clear

    php artisan config:clear

    php artisan route:clear

    View logs

    tail -f storage/logs/laravel.log

    Development routes

    http://localhost:8000/2fa/test # Test TOTP generation

    http://localhost:8000/2fa/test-encryption # Test encryption

    http://localhost:8000/2fa/bypass # Bypass 2FA (dev only)

    Customization

    #### Modify TOTP Settings

    // config/2fa.php

    'totp_digits' => 8, // Change to 8-digit codes

    'totp_period' => 60, // Change to 60-second intervals

    'totp_window' => 2, // Allow ±2 time steps

    #### Custom UI Styling

    / public/css/app.css /

    .glass-effect {

    background: rgba(255, 255, 255, 0.1);

    backdrop-filter: blur(10px);

    border: 1px solid rgba(255, 255, 255, 0.2);

    }

    ---

    🔒 Security

    Security Features

  • AES-256-CBC Encryption: All TOTP secrets are encrypted before storage
  • Time-based Validation: TOTP codes are only valid for 30 seconds
  • Window Tolerance: Allows for ±30 seconds of clock drift
  • Session Management: Secure 2FA verification flow
  • Rate Limiting: Protection against brute force attacks
  • No Third-party Dependencies: Custom TOTP implementation
  • Best Practices

  • Generate Unique Keys: Use different encryption keys for each environment
  • Secure Storage: Store encryption keys in environment variables
  • Regular Updates: Keep Laravel and dependencies updated
  • HTTPS Only: Use HTTPS in production
  • Session Security: Configure secure session settings
  • Security Checklist

  • [ ] Encryption keys are properly generated and stored
  • [ ] HTTPS is enabled in production
  • [ ] Session security is configured
  • [ ] Rate limiting is enabled
  • [ ] Error messages don't leak sensitive information
  • [ ] Development bypass is disabled in production
  • ---

    🤝 Contributing

    We welcome contributions! Please follow these steps:

  • Fork the repository
  • Create a feature branch (git checkout -b feature/amazing-feature)
  • Commit your changes (git commit -m 'Add amazing feature')
  • Push to the branch (git push origin feature/amazing-feature)
  • Open a Pull Request
  • Development Guidelines

  • Follow PSR-12 coding standards
  • Write tests for new features
  • Update documentation
  • Ensure security best practices

---

📄 License

This project is licensed under the MIT License - see the LICENSE file for details.

---

Made with ❤️ using Laravel, Tailwind CSS, and Alpine.js

⭐ Star this repo🐛 Report issues📖 Documentation