PHPackages                             salehye/laravel-security - PHPackages - PHPackages  [Skip to content](#main-content)[PHPackages](/)[Directory](/)[Categories](/categories)[Trending](/trending)[Leaderboard](/leaderboard)[Changelog](/changelog)[Analyze](/analyze)[Collections](/collections)[Log in](/login)[Sign up](/register)

1. [Directory](/)
2. /
3. [Authentication &amp; Authorization](/categories/authentication)
4. /
5. salehye/laravel-security

ActiveLaravel-package[Authentication &amp; Authorization](/categories/authentication)

salehye/laravel-security
========================

🔥 Advanced Security Package for Laravel 12 - The most comprehensive security solution for Laravel applications

v1.0.0(1mo ago)00MITPHPPHP ^8.2|^8.3|^8.4

Since Mar 27Pushed 1mo agoCompare

[ Source](https://github.com/salehye/laravel-security)[ Packagist](https://packagist.org/packages/salehye/laravel-security)[ Docs](https://github.com/salehye/laravel-security)[ GitHub Sponsors](https://github.com/sponsors/salehye)[ RSS](/packages/salehye-laravel-security/feed)WikiDiscussions main Synced 1mo ago

READMEChangelogDependencies (11)Versions (2)Used By (0)

Laravel Security Package
========================

[](#laravel-security-package)

🔥 **Advanced Security Package for Laravel 12** - The most comprehensive security solution for Laravel applications.

[![Latest Version on Packagist](https://camo.githubusercontent.com/36d816c1bc33b68d0779f201e34b98ee74b2b4aab2760d338a54ecf1222ee869/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f762f73616c656879652f6c61726176656c2d73656375726974792e7376673f7374796c653d666c61742d737175617265)](https://packagist.org/packages/salehye/laravel-security)[![Total Downloads](https://camo.githubusercontent.com/1b0f40f523e5e14456109dff2e6c732656507d646a935c31d59bf0091bfe91f5/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f64742f73616c656879652f6c61726176656c2d73656375726974792e7376673f7374796c653d666c61742d737175617265)](https://packagist.org/packages/salehye/laravel-security)[![License](https://camo.githubusercontent.com/88451d5529396bc4740400b0138b177ec49a598f14501ea1ff6a569f1b6d5535/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f6c2f73616c656879652f6c61726176656c2d73656375726974792e7376673f7374796c653d666c61742d737175617265)](https://github.com/salehye/laravel-security/blob/main/LICENSE)

Features
--------

[](#features)

### 🛡️ Comprehensive Protection

[](#️-comprehensive-protection)

- **Input Sanitization** - Automatic XSS prevention and input cleaning
- **SQL Injection Protection** - Advanced pattern detection and validation rules
- **XSS Protection** - Cross-site scripting prevention
- **Path Traversal Protection** - Directory traversal attack prevention
- **Command Injection Protection** - Shell command injection prevention

### 🔐 Authentication &amp; Session Security

[](#-authentication--session-security)

- **Brute Force Protection** - Rate-limited login attempts with progressive delays
- **Two-Factor Authentication (2FA)** - Built-in 2FA support
- **Session Hardening** - Session fixation prevention, concurrent session detection
- **Suspicious Login Detection** - Geographic anomaly detection, impossible travel detection
- **Re-authentication** - Require password for sensitive operations

### 🚦 Advanced Rate Limiting

[](#-advanced-rate-limiting)

- **Smart Rate Limiting** - IP, user, route, or combination-based limiting
- **Progressive Throttling** - Increasing penalties for repeat offenders
- **Endpoint-specific Limits** - Custom limits per route or endpoint

### 🔑 API Security

[](#-api-security)

- **Request Signing** - HMAC-based request integrity verification
- **Timestamp Verification** - Replay attack prevention
- **API Key Management** - Scoped API tokens with permissions
- **Nonce-based Protection** - One-time request tokens

### 📊 Audit &amp; Logging

[](#-audit--logging)

- **Comprehensive Audit Logs** - Track all security events
- **Multiple Channels** - Database, Log, Slack, SIEM integration
- **Real-time Alerts** - Instant notifications for critical events

### 🌐 Security Headers

[](#-security-headers)

- **Content Security Policy (CSP)** - Configurable CSP with nonce support
- **HSTS** - HTTP Strict Transport Security
- **X-Frame-Options** - Clickjacking prevention
- **X-Content-Type-Options** - MIME sniffing prevention
- **Referrer-Policy** - Referrer information control

Installation
------------

[](#installation)

```
# Install the package
composer require salehye/laravel-security

# Publish configuration and migrations
php artisan vendor:publish --provider="Salehye\LaravelSecurity\SecurityServiceProvider"
```

Configuration
-------------

[](#configuration)

After publishing, edit `config/security.php` to customize your security settings:

```
return [
    // Enable/disable the entire security package
    'enabled' => env('SECURITY_ENABLED', true),

    // Input protection settings
    'input_protection' => [
        'enabled' => true,
        'auto_sanitize' => true,
    ],

    // Firewall settings
    'firewall' => [
        'enabled' => true,
        'auto_block' => true,
        'threat_threshold' => 70,
    ],

    // Rate limiting
    'rate_limiting' => [
        'enabled' => true,
        'progressive' => [
            'enabled' => true,
            'threshold' => 3,
        ],
    ],

    // Security headers
    'headers' => [
        'enabled' => true,
        'csp' => [
            'enabled' => true,
        ],
    ],
];
```

Usage
-----

[](#usage)

### Middleware

[](#middleware)

The package automatically applies security middleware when `auto_protect` is enabled. You can also apply middleware manually:

```
// In app/Http/Kernel.php or bootstrap/app.php

protected $middlewareAliases = [
    'security.sanitize' => \Salehye\LaravelSecurity\Http\Middleware\SanitizeInputMiddleware::class,
    'security.rate' => \Salehye\LaravelSecurity\Http\Middleware\AdvancedRateLimitMiddleware::class,
    'security.headers' => \Salehye\LaravelSecurity\Http\Middleware\SecurityHeadersMiddleware::class,
    'security.api' => \Salehye\LaravelSecurity\Http\Middleware\ApiKeyMiddleware::class,
];
```

### Facade

[](#facade)

Use the `Security` facade for easy access to security features:

```
use Salehye\LaravelSecurity\Facades\Security;

// Audit logging
Security::audit(auth()->user(), 'updated_settings', $request->all());

// Block an IP
Security::blockIp('192.168.1.1', 'Brute force attack');

// Check if IP is blocked
if (Security::isBlocked($request->ip())) {
    abort(403, 'Access denied');
}

// Sanitize input
$clean = Security::sanitize($request->all());

// Detect threats
$threats = Security::detectThreats($request);
if (array_filter($threats)) {
    Security::logThreat('multiple_detections', $threats);
}

// Session management
Security::terminateAllOtherSessions($request);
```

### Validation Rules

[](#validation-rules)

The package provides custom validation rules:

```
use Salehye\LaravelSecurity\Rules\NoSqlInjectionRule;
use Salehye\LaravelSecurity\Rules\NoXssRule;
use Salehye\LaravelSecurity\Rules\SensitiveDataRule;
use Salehye\LaravelSecurity\Rules\PasswordStrengthRule;

// In your Form Request
public function rules(): array
{
    return [
        'username' => ['required', 'string', new NoSqlInjectionRule()],
        'comment' => ['required', 'string', new NoXssRule()],
        'data' => [new SensitiveDataRule()],
        'password' => ['required', new PasswordStrengthRule()],
    ];
}
```

### API Protection

[](#api-protection)

Sign your API requests:

```
use Salehye\LaravelSecurity\Facades\Security;

// Generate API key
$apiKey = Security::generateApiKey();

// Sign a request
$signedRequest = Security::signRequest($data, $apiKey);

// On the server side, verify the signature
if (!Security::verifySignature($request)) {
    abort(401, 'Invalid signature');
}
```

### Audit Logging

[](#audit-logging)

```
use Salehye\LaravelSecurity\Facades\Security;

// Log events
Security::log('user_login', auth()->user(), ['ip' => request()->ip()]);
Security::logFailedLogin($email, ['ip' => request()->ip()]);
Security::logSensitiveAction('password_change', auth()->user());
Security::logThreat('sql_injection', ['payload' => $request->get('search')]);

// Retrieve logs
$logs = Security::getLogs(event: 'login', limit: 100);

// Clean old logs
Security::cleanOldLogs(90); // Keep 90 days
```

Console Commands
----------------

[](#console-commands)

```
# Run security audit
php artisan security:audit

# Block an IP
php artisan security:block 192.168.1.1 --reason="Brute force" --duration=24

# Unblock an IP
php artisan security:unblock 192.168.1.1

# View security report
php artisan security:report

# Warmup security cache
php artisan security:cache:warmup

# Clean old audit logs
php artisan security:clean-logs --days=90
```

Events &amp; Listeners
----------------------

[](#events--listeners)

The package fires events for security-related actions:

```
// Events
\Salehye\LaravelSecurity\Events\SuspiciousActivityDetected::class
\Salehye\LaravelSecurity\Events\UserBlocked::class
\Salehye\LaravelSecurity\Events\LoginAttemptFailed::class
\Salehye\LaravelSecurity\Events\RateLimitExceeded::class
\Salehye\LaravelSecurity\Events\SensitiveActionPerformed::class
```

Testing
-------

[](#testing)

```
composer test
```

Documentation
-------------

[](#documentation)

For detailed documentation, visit the [Wiki](https://github.com/salehye/laravel-security/wiki).

Changelog
---------

[](#changelog)

Please see [CHANGELOG](CHANGELOG.md) for more information on what has changed recently.

Contributing
------------

[](#contributing)

Please see [CONTRIBUTING](CONTRIBUTING.md) for details.

Security
--------

[](#security)

If you discover any security-related issues, please email  instead of using the issue tracker.

Credits
-------

[](#credits)

- [Saleh Ye](https://github.com/salehye)
- [All Contributors](../../contributors)

License
-------

[](#license)

The MIT License (MIT). Please see [License File](LICENSE.md) for more information.

Laravel Package Development
---------------------------

[](#laravel-package-development)

This package is built following Laravel package development conventions and is compatible with Laravel 12.x and PHP 8.4+.

###  Health Score

38

—

LowBetter than 85% of packages

Maintenance90

Actively maintained with recent releases

Popularity0

Limited adoption so far

Community2

Small or concentrated contributor base

Maturity51

Maturing project, gaining track record

How is this calculated?**Maintenance (25%)** — Last commit recency, latest release date, and issue-to-star ratio. Uses a 2-year decay window.

**Popularity (30%)** — Total and monthly downloads, GitHub stars, and forks. Logarithmic scaling prevents top-heavy scores.

**Community (15%)** — Contributors, dependents, forks, watchers, and maintainers. Measures real ecosystem engagement.

**Maturity (30%)** — Project age, version count, PHP version support, and release stability.

###  Release Activity

Cadence

Unknown

Total

1

Last Release

46d ago

### Community

Maintainers

![](https://www.gravatar.com/avatar/8ebed43102dcdc037e65b6e6548f3dcc1aec28e1681913e6415c0f1c4cc0fd34?d=identicon)[salehye](/maintainers/salehye)

---

Tags

laravelsecurityAuthentication2faxsscsrfSQL Injectionfirewallprotectionlaravel12salehye

###  Code Quality

TestsPHPUnit

Static AnalysisPHPStan

Code StyleLaravel Pint

Type Coverage Yes

### Embed Badge

![Health badge](/badges/salehye-laravel-security/health.svg)

```
[![Health](https://phpackages.com/badges/salehye-laravel-security/health.svg)](https://phpackages.com/packages/salehye-laravel-security)
```

###  Alternatives

[hasinhayder/tyro

Tyro - The ultimate Authentication, Authorization, and Role &amp; Privilege Management solution for Laravel 12 &amp; 13

6712.1k2](/packages/hasinhayder-tyro)[sicaboy/laravel-mfa

A Laravel package of Multi-factor Authentication (MFA/2FA) with a middleware.

101.2k](/packages/sicaboy-laravel-mfa)

PHPackages © 2026

[Directory](/)[Categories](/categories)[Trending](/trending)[Changelog](/changelog)[Analyze](/analyze)
