Last updated: 25 November 2026. The scoring class and the rate limiter behavior were run and checked against laravel/framework 13.43.0. The listener, middleware and migration were syntax-checked and the migration was compiled to SQL, but I did not run them inside a full Laravel application. SeeHow this was checked.
A correct password does not prove the right person typed it. Credential stuffing and phished passwords both produce successful logins, and the only signals you get are around the login: which device, which network, which country, how many failures came first. This article shows how to score those signals in Laravel, what to do at each risk level, and where an existing package such as spatie/laravel-suspicious-login saves you the work. The aim is a small, explainable system, not a black box: every score comes with the reasons that produced it.
Decide what "suspicious" means for your app
Each signal is weak alone and misleading in some cases. A new device is normal after a laptop upgrade. A new country is normal on holiday, and VPN users change country every session. Scoring lets several weak signals add up before you act. A reasonable policy has three levels:
- Low: record the login and do nothing visible.
- Medium: tell the user by email ("Was this you?") with the time, place and device, and a link to change the password.
- High: require a second step, such as an emailed code, before the session can be used.
Blocking outright on weak signals locks real users out and teaches them to ignore your emails. Prefer a step-up challenge over a hard block unless the signal is strong, for example many failed attempts followed by a success from a new country.
Option 1: use a package
The Spatie package scores logins from device, IP and country history and lets you pick the response. Its documentation lists these checks with their default scores: new device 25, new IP address 10, new country 30, multiple countries within an hour 40, impossible travel 60, allowed and blocked countries 50, failed attempts 30, credential stuffing 40, unusual time 15, suspicious user agent 20 and IP reputation 50. You choose the checks, the scores and the actions in a preset. In the documentation's example, medium risk starts at 40 and high at 70; a high-risk login runs the notify action and a block action that marks the attempt as blocked, logs the user out and throws a validation exception. The requirements page lists PHP 8.4 or higher and Laravel 11 or higher.
The docs also state caveats worth repeating: failed logins are recorded but not scored, failed or blocked attempts do not make a device or country familiar, and VPNs and legitimate travel can trigger the country check. I did not install or run the package, since package downloads were blocked in my environment, so check its current documentation before you adopt it.
Use a package when you want impossible-travel and IP reputation checks, which need geolocation data and are tedious to build. Build your own when you need full control, a short dependency list, or an older PHP version. The rest of this article builds the core yourself.
Option 2: build it
Step 1: store what you need to compare
You need a history of successful logins per user: device, network, country and the score you gave. This migration creates it:
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
return new class extends Migration
{
public function up(): void
{
Schema::create('login_events', function (Blueprint $table) {
$table->id();
$table->foreignId('user_id')->constrained()->cascadeOnDelete();
$table->string('device_id', 64);
$table->string('network', 64); // /24 or /64 prefix, see networkPrefix()
$table->string('ip', 45);
$table->string('country', 2)->nullable();
$table->string('user_agent', 255)->nullable();
$table->unsignedSmallInteger('score')->default(0);
$table->string('level', 8)->default('low');
$table->timestamps();
$table->index(['user_id', 'created_at']);
});
}
public function down(): void
{
Schema::dropIfExists('login_events');
}
};
I compiled this migration with Laravel's MySQL schema grammar and got the expected table, a cascading foreign key to users and a composite index on user_id, created_at. The network column stores an IPv4 /24 or IPv6 /64 prefix, which keeps a phone that hops between addresses in one network from looking new. Treat IP addresses as personal data: decide how long you keep them and delete old rows on a schedule.
Step 2: a scorer you can test
Put the risk logic in a plain class with no framework dependencies, so you can unit test every combination. This is the one I ran:
<?php
declare(strict_types=1);
namespace App\Security;
final class LoginRiskScorer
{
public const MEDIUM = 40;
public const HIGH = 70;
public function __construct(
private int $newDevice = 25,
private int $newNetwork = 10,
private int $newCountry = 30,
private int $recentFailures = 30,
private int $failureThreshold = 5,
) {}
/**
* @param string[] $knownDevices device ids seen on previous successful logins
* @param string[] $knownNetworks network prefixes (see networkPrefix()) seen before
* @param string[] $knownCountries ISO country codes seen before
* @return array{score:int, level:string, reasons:string[]}
*/
public function assess(
string $deviceId,
string $ip,
?string $country,
array $knownDevices,
array $knownNetworks,
array $knownCountries,
int $failuresInLastHour,
): array {
// No history yet: the first successful login has nothing to compare with.
if ($knownDevices === [] && $knownNetworks === [] && $knownCountries === []) {
return ['score' => 0, 'level' => 'low', 'reasons' => []];
}
$score = 0;
$reasons = [];
if (! in_array($deviceId, $knownDevices, true)) {
$score += $this->newDevice;
$reasons[] = 'new device';
}
if (! in_array(self::networkPrefix($ip), $knownNetworks, true)) {
$score += $this->newNetwork;
$reasons[] = 'new network';
}
if ($country !== null && $knownCountries !== [] && ! in_array($country, $knownCountries, true)) {
$score += $this->newCountry;
$reasons[] = 'new country';
}
if ($failuresInLastHour >= $this->failureThreshold) {
$score += $this->recentFailures;
$reasons[] = 'many recent failed logins';
}
$level = $score >= self::HIGH ? 'high' : ($score >= self::MEDIUM ? 'medium' : 'low');
return ['score' => $score, 'level' => $level, 'reasons' => $reasons];
}
/** IPv4 /24 or IPv6 /64, so a phone changing address inside one network is not "new". */
public static function networkPrefix(string $ip): string
{
$bin = inet_pton($ip);
if ($bin === false) {
return $ip;
}
if (strlen($bin) === 4) {
return implode('.', array_slice(explode('.', $ip), 0, 3)).'.0/24';
}
return bin2hex(substr($bin, 0, 8)).'::/64';
}
}
The weights here are my starting values, similar in spirit to the package defaults, not a standard. With the default weights, a run of nine cases produced this:
first login (no history) 0 low
known device/network/country 0 low
new device only 25 low new device
new network only 10 low new network
new country only 30 low new country
new device + new country 55 medium new device, new country
new device + network + country 65 medium new device, new network, new country
known all but 6 recent failures 30 low many recent failed logins
unknown country (null) new device 25 low new device
Two things to notice. The first login scores 0 because there is no history to compare against. And an unknown country (a null header) never counts as new, so a missing header does not raise the score. With a threshold of 70, nothing in this table reaches high; it takes a new device, a new country and a burst of failures, which is what you want, since high triggers a challenge. The network prefix helper turned both 203.0.113.5 and 203.0.113.250 into 203.0.113.0/24, and two IPv6 addresses in the same /64 into the same prefix.
Step 3: count failed logins
Laravel fires Illuminate\Auth\Events\Failed with the submitted credentials when an attempt fails. A listener can count failures per email in the rate limiter, which gives the scorer its failure input:
<?php
namespace App\Listeners;
use Illuminate\Auth\Events\Failed;
use Illuminate\Support\Facades\RateLimiter;
use Illuminate\Support\Str;
class CountFailedLogin
{
public function handle(Failed $event): void
{
$email = $event->credentials['email'] ?? null;
if (is_string($email) && $email !== '') {
// One hour window, keyed by a hash so the address is not stored in the cache key.
RateLimiter::hit('failed:'.sha1(Str::lower($email)), 3600);
}
}
}
I ran the real RateLimiter against an array cache store with a limit of 5: the first five checks returned false, the sixth, after five hits, returned true, attempts() reported 6 after the sixth hit, and clear() reset it. Hash the email in the key, as above, so the address does not appear in cache keys. Remember that this counts per account. To catch credential stuffing, where one IP tries many accounts, add a second counter keyed by IP and count distinct emails.
Step 4: score on login
The Login event carries the guard, the user and the remember flag. This listener scores the login, records it, notifies the user and sets a session flag for high risk:
<?php
namespace App\Listeners;
use App\Models\LoginEvent;
use App\Notifications\RiskyLoginNotification;
use App\Security\LoginRiskScorer;
use Illuminate\Auth\Events\Login;
use Illuminate\Support\Facades\Cookie;
use Illuminate\Support\Facades\RateLimiter;
use Illuminate\Support\Str;
class AssessLogin
{
public function __construct(private LoginRiskScorer $scorer) {}
public function handle(Login $event): void
{
$request = request();
// Login also fires when a user is restored from the "remember me" cookie.
// Only score the request that actually submitted the login form.
if (! $request->isMethod('POST') || ! $request->routeIs('login*')) {
return;
}
$user = $event->user;
$deviceId = $request->cookie('device_id') ?: Str::uuid()->toString();
Cookie::queue(Cookie::make('device_id', $deviceId, 60 * 24 * 365, null, null, true, true));
$ip = $request->ip();
$network = LoginRiskScorer::networkPrefix($ip);
$country = $request->header(config('security.country_header', 'CF-IPCountry'));
$history = LoginEvent::where('user_id', $user->getAuthIdentifier())->get(['device_id', 'network', 'country']);
$failures = RateLimiter::attempts('failed:'.sha1(Str::lower($user->email)));
$result = $this->scorer->assess(
$deviceId,
$ip,
$country,
$history->pluck('device_id')->unique()->all(),
$history->pluck('network')->unique()->all(),
$history->pluck('country')->filter()->unique()->all(),
$failures,
);
LoginEvent::create([
'user_id' => $user->getAuthIdentifier(),
'device_id' => $deviceId,
'network' => $network,
'ip' => $ip,
'country' => $country,
'user_agent' => Str::limit((string) $request->userAgent(), 255, ''),
'score' => $result['score'],
'level' => $result['level'],
]);
if ($result['level'] !== 'low') {
$user->notify(new RiskyLoginNotification($result, $ip, $country));
}
if ($result['level'] === 'high') {
// Step-up: the session exists, but it cannot be used until the challenge passes.
session(['login_challenge' => true]);
}
}
}
Read the first guard clause carefully. In the framework source, the session guard also fires Login when it restores a user from the "remember me" cookie, with the remember flag set to true. A listener that does not filter would score every remember-cookie session as a fresh login and spam users. Restricting it to the POST request of the login route avoids that; adjust the route pattern to your app. Also note:
- The device identifier is a random value in a long-lived cookie, not a hash of the user agent. A user agent string changes with every browser update and is shared by many people.
-
CF-IPCountryis only trustworthy if every request really passes through Cloudflare. Without a trusted source, set the country to null and rely on device and network signals. Never trust a country header a client can set directly. -
$request->ip()behind a load balancer or CDN is only correct if you configured trusted proxies. Check it before relying on network history. - Make
RiskyLoginNotificationimplementShouldQueueso a slow mail server does not slow down logins.
Step 5: step-up on high risk
The listener only sets a session flag. A middleware turns that flag into a gate, so the session cannot reach anything except the challenge page and logout until the user passes it:
<?php
namespace App\Http\Middleware;
use Closure;
use Illuminate\Http\Request;
use Symfony\Component\HttpFoundation\Response;
class RequireLoginChallenge
{
public function handle(Request $request, Closure $next): Response
{
if ($request->session()->get('login_challenge') && ! $request->routeIs('login.challenge*', 'logout')) {
return redirect()->route('login.challenge');
}
return $next($request);
}
}
Register it on your authenticated route group. The challenge itself, emailing a one-time code and clearing the flag when the code is correct, is not shown here, and I did not test this flow in an application. Do not clear the flag until the code verifies, and expire codes quickly. This design deliberately avoids throwing an exception from inside the Login listener, which makes failures harder to reason about.
Testing it
Unit test the scorer first, since it has no dependencies; the table above is a good starting set of cases. Then add feature tests for the listener: log in once to build history, log in again with a different device_id cookie and country header, and assert that a notification was sent and the session flag is set. Add one test that restores a user from a remember cookie and asserts that no new login row is written.
Pitfalls
- Alert fatigue. If every new device emails the user, they stop reading the emails. Notify at medium, not low.
- VPN users. Their country and IP change constantly. Rely more on the device cookie for them, and allow a "trust this device" action.
- Cleared cookies. A user who clears cookies becomes a new device. That is acceptable at a score of 25, but not if you block on it.
- Do not reveal the reason. Show the user a generic challenge message. Reasons belong in your logs and in the email, not on the login form.
- Passwords still matter. Scoring complements rate limiting, strong password rules and two-factor authentication. It does not replace them.
Related Dev Talk articles
- SQL Injection in PHP: PDO and MySQLi Prevention
- Laravel Queue Jobs Not Processing: Causes and Fixes
- Laravel Notifications After Commit
Frequently asked questions
How do I detect suspicious logins in Laravel?
Record the device, network and country of each successful login, compare new logins against that history, add the weights of the signals that differ, and act on the total: notify at medium risk and require a second step at high risk.
Which Laravel event should I listen to?
Use Illuminate\Auth\Events\Login for successful logins and Illuminate\Auth\Events\Failed for failures. Filter Login to the login request, because it also fires when a user is restored from a remember-me cookie.
Is there a package for this?
Yes. spatie/laravel-suspicious-login scores logins from device, IP and location history and can notify users or block high-risk logins. Its documentation lists PHP 8.4 or higher and Laravel 11 or higher.
Should I block risky logins automatically?
Only for strong combinations of signals. For most apps a step-up challenge, such as an emailed code, is safer than a hard block, which locks out legitimate users.
Can I use the user agent as the device identifier?
It is a weak identifier. It changes with browser updates and many people share the same string. A random cookie value stored per browser is more reliable.
Does this stop credential stuffing?
It helps, but rate limiting per IP and per account, breached-password checks and two-factor authentication matter more. Scoring catches the successful logins that slip through.
update log
- 25 November 2026: first version.
-
To recheck on each update: the package's version, requirements and default scores, whether the framework's remember-cookie
Loginbehavior has changed, and the Laravel version used here.
Sources
- Spatie: laravel-suspicious-login, getting started
- Spatie: available checks overview
- Spatie: requirements
- Laravel documentation: Authentication
- laravel/framework: SessionGuard.php
Originally published on DEV Talk.
Top comments (1)
The remember-me cookie detail is the one most implementations get wrong — scoring a session restore as a fresh login would flag every returning user. Storing the network as a /24 or /64 prefix is the other quiet win: a phone hopping IPs stays one network instead of looking like a new attacker every time. One question: for the medium tier, do you find users actually act on the "Was this you?" email, or does it mostly become noise they ignore until the high-risk step-up fires?