Getting started | laravel-suspicious-login | Spatie       

 SPATIE  

  Laravel Suspicious Login      Laravel Suspicious Login 
=========================================================

spatie.be/open-source

  [Docs](https://spatie.be/docs)  [Laravel-suspicious-login](https://spatie.be/docs/laravel-suspicious-login/v1)  Basic-usage  Getting started

 Version   v1      

 Other versions for crawler [v1](https://spatie.be/docs/laravel-suspicious-login/v1) 

  Getting started    
- [ Introduction ](https://spatie.be/docs/laravel-suspicious-login/v1/introduction)
- [ Support us ](https://spatie.be/docs/laravel-suspicious-login/v1/support-us)
- [ Requirements ](https://spatie.be/docs/laravel-suspicious-login/v1/requirements)
- [ Installation &amp; setup ](https://spatie.be/docs/laravel-suspicious-login/v1/installation-setup)
- [ Questions and issues ](https://spatie.be/docs/laravel-suspicious-login/v1/questions-issues)
- [ Changelog ](https://spatie.be/docs/laravel-suspicious-login/v1/changelog)
- [ About us ](https://spatie.be/docs/laravel-suspicious-login/v1/about-us)

Basic usage
-----------

- [ Getting started ](https://spatie.be/docs/laravel-suspicious-login/v1/basic-usage/getting-started)
- [ How a login is scored ](https://spatie.be/docs/laravel-suspicious-login/v1/basic-usage/how-a-login-is-scored)
- [ Choosing a preset ](https://spatie.be/docs/laravel-suspicious-login/v1/basic-usage/choosing-a-preset)
- [ Customizing presets ](https://spatie.be/docs/laravel-suspicious-login/v1/basic-usage/customizing-presets)
- [ Working with login attempts ](https://spatie.be/docs/laravel-suspicious-login/v1/basic-usage/working-with-login-attempts)
- [ Adding custom properties ](https://spatie.be/docs/laravel-suspicious-login/v1/basic-usage/adding-custom-properties)
- [ Recording logins manually ](https://spatie.be/docs/laravel-suspicious-login/v1/basic-usage/recording-logins-manually)

Available checks
----------------

- [ Overview ](https://spatie.be/docs/laravel-suspicious-login/v1/available-checks/overview)
- [ New device ](https://spatie.be/docs/laravel-suspicious-login/v1/available-checks/new-device)
- [ New IP address ](https://spatie.be/docs/laravel-suspicious-login/v1/available-checks/new-ip)
- [ New country ](https://spatie.be/docs/laravel-suspicious-login/v1/available-checks/new-country)
- [ Impossible travel ](https://spatie.be/docs/laravel-suspicious-login/v1/available-checks/impossible-travel)
- [ Allowed and blocked countries ](https://spatie.be/docs/laravel-suspicious-login/v1/available-checks/country)
- [ Failed attempts ](https://spatie.be/docs/laravel-suspicious-login/v1/available-checks/failed-attempts)
- [ Credential stuffing ](https://spatie.be/docs/laravel-suspicious-login/v1/available-checks/credential-stuffing)
- [ Unusual time ](https://spatie.be/docs/laravel-suspicious-login/v1/available-checks/unusual-time)
- [ Suspicious user agent ](https://spatie.be/docs/laravel-suspicious-login/v1/available-checks/suspicious-user-agent)
- [ IP reputation ](https://spatie.be/docs/laravel-suspicious-login/v1/available-checks/ip-reputation)
- [ Multiple countries ](https://spatie.be/docs/laravel-suspicious-login/v1/available-checks/multiple-countries)

Responding to suspicious logins
-------------------------------

- [ Notifying users ](https://spatie.be/docs/laravel-suspicious-login/v1/responding-to-suspicious-logins/notifying-users)
- [ Blocking logins ](https://spatie.be/docs/laravel-suspicious-login/v1/responding-to-suspicious-logins/blocking-logins)
- [ Writing your own actions ](https://spatie.be/docs/laravel-suspicious-login/v1/responding-to-suspicious-logins/writing-your-own-actions)
- [ Using events ](https://spatie.be/docs/laravel-suspicious-login/v1/responding-to-suspicious-logins/using-events)

Advanced usage
--------------

- [ Creating custom checks ](https://spatie.be/docs/laravel-suspicious-login/v1/advanced-usage/creating-custom-checks)
- [ Geolocation drivers ](https://spatie.be/docs/laravel-suspicious-login/v1/advanced-usage/geolocation-drivers)
- [ IP reputation drivers ](https://spatie.be/docs/laravel-suspicious-login/v1/advanced-usage/ip-reputation-drivers)
- [ Device fingerprints ](https://spatie.be/docs/laravel-suspicious-login/v1/advanced-usage/device-fingerprints)
- [ Using your own model ](https://spatie.be/docs/laravel-suspicious-login/v1/advanced-usage/using-your-own-model)

 Getting started
===============

###  On this page 

1. [ Install the package ](#content-install-the-package)
2. [ Create a preset ](#content-create-a-preset)
3. [ Configure the package ](#content-configure-the-package)
4. [ What happens at login ](#content-what-happens-at-login)
5. [ Inspect login attempts ](#content-inspect-login-attempts)
6. [ Customize further ](#content-customize-further)

This example adds suspicious-login detection to a Laravel application with session-based authentication. We'll notify users when they log in from a new country, and block the login when the device is new too.

The package listens to Laravel's authentication events. You don't need to change your login controller when it already uses Laravel's authentication system.

Install the package
-----------------------------------------------------------------------------------------------------------------

```
composer require spatie/laravel-suspicious-login
php artisan suspicious-login:install
```

The install command publishes `config/suspicious-login.php` and the migration for the `login_attempts` table. Accept its offer to run migrations, or run `php artisan migrate` yourself. See [installation and setup](/docs/laravel-suspicious-login/v1/installation-setup) for the complete config and manual publishing commands.

Create a preset
-----------------------------------------------------------------------------------------------------

A preset chooses the checks to run, their scores, and the actions for medium and high risk. Create `app/SuspiciousLogin/ProtectLogins.php`:

```
namespace App\SuspiciousLogin;

use Spatie\SuspiciousLogin\Actions\Action;
use Spatie\SuspiciousLogin\Actions\BlockLoginAction;
use Spatie\SuspiciousLogin\Actions\NotifyUserAction;
use Spatie\SuspiciousLogin\Checks\NewCountryCheck;
use Spatie\SuspiciousLogin\Checks\NewDeviceCheck;
use Spatie\SuspiciousLogin\Presets\Preset;

class ProtectLogins extends Preset
{
    public function checks(): array
    {
        return [
            NewDeviceCheck::new()->score(30),
            NewCountryCheck::new()->score(40),
        ];
    }

    public function onMediumRisk(): Action|array
    {
        return NotifyUserAction::new();
    }

    public function onHighRisk(): Action|array
    {
        return [
            NotifyUserAction::new(),
            BlockLoginAction::new(),
        ];
    }
}
```

Each check adds its score when it flags the login. `NotifyUserAction` sends the user an email; `BlockLoginAction` marks the attempt as blocked, logs the user out, and throws a validation exception. Put blocking last because it ends the request. High risk runs only `onHighRisk()`, not the medium-risk actions as well.

You can also [choose a built-in preset](/docs/laravel-suspicious-login/v1/basic-usage/choosing-a-preset) instead of writing one. The default `Balanced` preset notifies users without blocking them. See [customizing presets](/docs/laravel-suspicious-login/v1/basic-usage/customizing-presets) for extending a built-in preset.

Configure the package
-----------------------------------------------------------------------------------------------------------------------

In the published `config/suspicious-login.php`, set these values, leaving the other options in place:

```
'preset' => App\SuspiciousLogin\ProtectLogins::class,

'risk_thresholds' => [
    'medium' => 40,
    'high' => 70,
],

'geolocation' => [
    'driver' => 'ipinfo',
    'cache_ttl' => 60 * 60 * 24 * 7,

    'ipinfo' => [
        'token' => null,
    ],
],
```

The `ipinfo` driver is the default and works without a token, subject to ipinfo's limits. It sends public IP addresses to ipinfo.io and caches locations for a week. If the lookup fails, the country check passes. You can [use Cloudflare, MaxMind, or another geolocation driver](/docs/laravel-suspicious-login/v1/advanced-usage/geolocation-drivers) instead. Setting the driver to `'null'` disables location lookups.

To receive the notification, your user model needs Laravel's `Notifiable` trait and your application needs working mail configuration. The notification is queued, so run a queue worker unless your queue connection is `sync`. See [notifying users](/docs/laravel-suspicious-login/v1/responding-to-suspicious-logins/notifying-users) for customizing the email, and [blocking logins](/docs/laravel-suspicious-login/v1/responding-to-suspicious-logins/blocking-logins) for changing the rejection response.

What happens at login
-----------------------------------------------------------------------------------------------------------------------

Suppose Anna has already logged in successfully from her usual browser in Belgium. With this preset:

LoginScoreRiskResultKnown device, known country0lowRecord the attempt; no actionNew device, known country30lowRecord the attempt; no actionKnown device, new country40mediumRecord the attempt and notify AnnaNew device, new country70highRecord the attempt, notify Anna, and block the loginThe first login has no history to compare against, so these two checks don't flag it. Failed logins are recorded but aren't scored, and failed or blocked attempts don't make a device or country familiar. VPNs and legitimate travel can trigger the country check; choose scores and actions that suit your application.

Read [how a login is scored](/docs/laravel-suspicious-login/v1/basic-usage/how-a-login-is-scored) for the full lifecycle and [available checks](/docs/laravel-suspicious-login/v1/available-checks/overview) for other signals you can add.

Inspect login attempts
--------------------------------------------------------------------------------------------------------------------------

Query the recorded attempts through the `LoginAttempt` model:

```
use Spatie\SuspiciousLogin\Models\LoginAttempt;

$attempts = LoginAttempt::query()
    ->whereMorphedTo('authenticatable', $user)
    ->latest()
    ->limit(10)
    ->get();

foreach ($attempts as $attempt) {
    $attempt->risk_score;
    $attempt->risk_level;
    $attempt->reasons;
    $attempt->blocked;
}
```

`reasons` contains the flagged checks, their scores, and their explanations. `risk_level` is a `RiskLevel` enum on assessed attempts; failed logins have no risk level. See [working with login attempts](/docs/laravel-suspicious-login/v1/basic-usage/working-with-login-attempts) for history queries and pruning.

Customize further
-----------------------------------------------------------------------------------------------------------

- [Add custom properties](/docs/laravel-suspicious-login/v1/basic-usage/adding-custom-properties) to store application context with each attempt.
- [Record logins manually](/docs/laravel-suspicious-login/v1/basic-usage/recording-logins-manually) when your authentication flow doesn't fire Laravel's events. Don't combine manual and automatic recording for the same login.
- [Write your own checks](/docs/laravel-suspicious-login/v1/advanced-usage/creating-custom-checks) for application-specific signals.
- [Write your own actions](/docs/laravel-suspicious-login/v1/responding-to-suspicious-logins/writing-your-own-actions) or [listen for events](/docs/laravel-suspicious-login/v1/responding-to-suspicious-logins/using-events) to integrate with other services.

 A good
match?
-------------

### What we do best

- All things Laravel
- Custom frontend components
- Building APIs
- AI-powered features
- Simplifying things
- Clean solutions
- Integrating services

### Not our cup of tea

- WordPress themes
- Cutting corners
- Free mockups to win a job
- "Just execute the briefing"

 In short: we'd like to be a **substantial part** of your project.

 [ Get in touch via email ](mailto:info@spatie.be?subject=A%20good%20match%21&body=Tell%20us%20as%20much%20as%20you%20can%20about%0A-%20your%20online%20project%0A-%20your%20planning%0A-%20your%20budget%0A-%20%E2%80%A6%0A%0AAnything%20that%20helps%20us%20to%20start%20straightforward%21)
