Skip to content

Instantly share code, notes, and snippets.

@jaygaha
Created February 6, 2024 02:47
Show Gist options
  • Save jaygaha/40ca9cf489ce4333e991011b7914300a to your computer and use it in GitHub Desktop.
Save jaygaha/40ca9cf489ce4333e991011b7914300a to your computer and use it in GitHub Desktop.
Laravel Sanctum auto logout if authenticated user remains idle for certain time

Laravel Sanctum auto logout if user remains idle for certain time

Ensuring the security of user sessions is critical in web applications, and Laravel Sanctum offers a strong solution for API authentication in Laravel projects. Implementing an automatic logout function when users are idle for an extended length of time is critical for improving security and user privacy. In this post, we'll look at how to integrate idle timeout capabilities with the Laravel API using Sanctum. Let's look at how to set up automated user logout for inactive sessions in a Laravel Sanctum-powered API.

Registering a custom validation with Sanctum

Open AuthServiceProvider.php and add this code accordingly to this file:

use Carbon\Carbon;
use Laravel\Sanctum\PersonalAccessToken;
use Laravel\Sanctum\Sanctum;
 
class AuthServiceProvider extends ServiceProvider
{
    // ...
    public function boot()
    {
        // ...
        Sanctum::authenticateAccessTokensUsing(
            static function (PersonalAccessToken $accessToken, bool $isValid) {
               $idleTime = config('sanctum.lifetime'); // Set the idle time in minutes
			   
                return $isValid && (
                    $accessToken->last_used_at === null
                    || $accessToken->last_used_at->gt(Carbon::now()->subMinutes($idleTime))
                );
            }
        );
    }
}

It checks if the access token is valid and if it has been used within the last minute. If both conditions are met, the access token is considered valid.

Here's a breakdown of the code:

  • Sanctum::authenticateAccessTokensUsing: This method is used to customize the logic for authenticating access tokens.
  • static function (PersonalAccessToken $accessToken, bool $isValid): This is a closure (anonymous function) that takes two parameters: $accessToken and $isValid. $accessToken is an instance of PersonalAccessToken, which represents an access token in the application. $isValid is a boolean value that indicates whether the access token is valid or not.
  • $idleTime = config('sanctum.lifetime');: This line retrieves the idle time (in minutes) from the configuration file. The idle time is the maximum amount of time that can pass between two uses of the access token before it is considered expired.
  • return $isValid && (...): This line returns the result of the logical AND operation between $isValid and the result of the condition inside the parentheses. The condition checks if the access token has been used before and if it was used within the last minute. If both conditions are met, the access token is considered valid.

In summary, this code customizes the access token authentication logic in Laravel Sanctum to consider an access token valid only if it is valid and has been used within the last minute. This ensures that access tokens are refreshed periodically to maintain security.

Ref: https://doeken.org/blog/custom-access-tokens-laravel-sanctum

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment