spatie / laravel-suspicious-login
Detect suspicious logins in your Laravel app and decide how to respond
Package info
github.com/spatie/laravel-suspicious-login
pkg:composer/spatie/laravel-suspicious-login
Fund package maintenance!
Requires
- php: ^8.4
- illuminate/contracts: ^11.0||^12.0||^13.0
- spatie/laravel-package-tools: ^1.16
Requires (Dev)
- geoip2/geoip2: ^3.0
- larastan/larastan: ^3.0
- laravel/pint: ^1.14
- nunomaduro/collision: ^8.8
- orchestra/testbench: ^11.0.0||^10.0.0||^9.0.0
- pestphp/pest: ^4.0||^5.0
- pestphp/pest-plugin-arch: ^4.0||^5.0
- pestphp/pest-plugin-laravel: ^4.0||^5.0
- phpstan/extension-installer: ^1.4
- phpstan/phpstan-deprecation-rules: ^2.0
- phpstan/phpstan-phpunit: ^2.0
Suggests
- geoip2/geoip2: Required to use the maxmind geolocation driver (^3.0).
Provides
None
Conflicts
None
Replaces
None
README
Detect suspicious logins in your Laravel app
A login with the correct password can still come from an attacker. This package looks at everything around that login (the device, the IP address, where it comes from, how many attempts failed before it) and gives it a risk score. Depending on the score, it can notify the user, block the login, or do whatever you want.
Here's how a login from a new laptop in New York, to an account that always logs in from Antwerp, is scored with the default Balanced preset and geolocation configured:
Login from a new device +25
Login from a new IP address (5.6.7.8) +10
Login from a new country (US) +30
----
Risk score 65 → medium risk, the user gets an email
A preset lists the checks to run, how much each weighs, and which actions run at each risk level. It can also override the default risk thresholds from the config file. The package ships with Lenient, Balanced, Strict and MonitorOnly presets, and writing your own takes a few lines:
namespace App\SuspiciousLogin; use Spatie\SuspiciousLogin\Actions\Action; use Spatie\SuspiciousLogin\Actions\BlockLoginAction; use Spatie\SuspiciousLogin\Actions\NotifyUserAction; use Spatie\SuspiciousLogin\Checks\CountryCheck; use Spatie\SuspiciousLogin\Checks\ImpossibleTravelCheck; use Spatie\SuspiciousLogin\Checks\NewDeviceCheck; use Spatie\SuspiciousLogin\Presets\Preset; class MyPreset extends Preset { public function checks(): array { return [ NewDeviceCheck::new()->score(30), ImpossibleTravelCheck::new()->maxSpeedInKilometersPerHour(1000)->score(60), CountryCheck::new()->onlyAllow(['BE', 'NL', 'FR'])->score(60), ]; } public function onMediumRisk(): Action|array { return NotifyUserAction::new(); } public function onHighRisk(): Action|array { return [NotifyUserAction::new(), BlockLoginAction::new()]; } }
Register your preset in config/suspicious-login.php:
'preset' => App\SuspiciousLogin\MyPreset::class,
The default risk thresholds live in config/suspicious-login.php:
'risk_thresholds' => [ 'medium' => 40, 'high' => 70, ],
Optionally define protected int $mediumRiskThreshold or protected int $highRiskThreshold in your preset to override either config value. Balanced and MonitorOnly use the configured defaults; Strict defines 30/60 and Lenient defines 50/80.
Only the actions for the matching level run. List BlockLoginAction last because it logs the user out of their session guard and throws a validation exception.
An action is a small class with an execute method that receives the login attempt. There's no magic behind the ones the package ships with. Here's BlockLoginAction in full:
class BlockLoginAction extends Action { protected string $errorKey = 'email'; protected string $message = 'We blocked this login because it looked suspicious. Please contact support if this was you.'; public function errorKey(string $errorKey): static { $this->errorKey = $errorKey; return $this; } public function message(string $message): static { $this->message = $message; return $this; } public function execute(LoginAttempt $attempt): void { $attempt->update(['blocked' => true]); event(new SuspiciousLoginBlockedEvent($attempt)); Auth::guard($attempt->guard)->logout(); $this->respond($attempt); } protected function respond(LoginAttempt $attempt): never { throw ValidationException::withMessages([ $this->errorKey => __($this->message), ]); } }
new() comes from the base Action class and resolves the action from the container, so actions can inject dependencies in their constructor. The fluent methods configure it in your preset, like BlockLoginAction::new()->message('...'). Because the login happens inside Auth::attempt(), the validation exception comes out of your login controller like any other validation error.
To change the response without replacing the blocking and logout behavior, extend BlockLoginAction and override protected function respond(LoginAttempt $attempt): never. See customizing the response.
Writing your own action, for example to ask for a second factor or alert your security team, works the same way: extend Action and implement execute. Checks are built the same way too: extend Check and return $this->pass() or $this->flag($reason) from evaluate.
You can also add MultipleCountriesCheck to your preset to flag logins from different countries within one hour, even when both countries are already known.
Checks, actions, geolocation and IP reputation drivers, device fingerprints and the model are all swappable, and the package fires events you can listen for.
Support us
We invest a lot of resources into creating best in class open source packages. You can support us by buying one of our paid products.
We highly appreciate you sending us a postcard from your hometown, mentioning which of our package(s) you are using. You'll find our address on our contact page. We publish all received postcards on our virtual postcard wall.
Installation
You can install the package via composer:
composer require spatie/laravel-suspicious-login
Run the install command:
php artisan suspicious-login:install
It publishes config/suspicious-login.php and the migration for the login_attempts table, then asks whether to run your application's pending migrations. If you decline, run php artisan migrate before using the package. It also offers to star the repository on GitHub.
That's it. The package listens for Laravel's Login and Failed auth events, so it works with Breeze, Jetstream, Fortify and your own login controllers without changes. Logins restored from a "remember me" cookie are not recorded.
Out of the box the Balanced preset is used, and the ipinfo driver looks up public IP addresses without requiring an API token. Lookups are cached for a week and subject to ipinfo's limits. You can choose another geolocation driver in config/suspicious-login.php, or set it to 'null' to disable lookups and avoid sending IP addresses to an external service.
The default notification requires Laravel's Notifiable trait on your user model and working mail configuration. It is queued, so run a queue worker unless you use the sync queue connection.
You can publish the email's Markdown view to change its content or layout without replacing the notification.
For an existing application, consider starting with Spatie\SuspiciousLogin\Presets\MonitorOnly. It records scores and fires events without notifying or blocking users, so you can review the results before enabling actions.
Documentation
All documentation is available on our documentation site.
- Get started with a complete example.
- Choose a preset or customize one.
- Query login attempts and add custom properties.
- Write checks, write actions, or listen for events.
Laravel Boost
The package ships guidelines and a detecting-suspicious-logins skill for Laravel Boost. Run php artisan boost:install in your application and select this package to give your coding agent its APIs, extension points, and usage examples. See the setup instructions.
Testing
composer test
Changelog
Please see CHANGELOG for more information on what has changed recently.
Contributing
Please see CONTRIBUTING for details.
Security Vulnerabilities
Please review our security policy on how to report security vulnerabilities.
Credits
License
The MIT License (MIT). Please see License File for more information.