laravellaravel-sanctum

Laravel Sanctum: How to configure the expiration date of the token?


Context and Need

In my api routes file, I've written the following code following the documentation (https://laravel.com/docs/8.x/sanctum#introduction) :

Route::post('/tokens/create', function (Request $request) {
    $token = $request->user()->createToken($request->token_name);
    return ['token' => $token->plainTextToken];
});

I would want to set an expiration delay that would be used to compare the date of the creation of the token with the date of the current check of the token expiration: the token'd have a creation date of x, the current date'd be y, and the delay'd be d so the token would expire if y > x + d.

What I've done

So I've read some code in the directory vendor/laravel/sanctum, and I've found the class Guard.php.

The class Guard.php contains an object attribute named $expiration, a constructor that sets it (among other things), and the __invoke method that contains the following expiration check:

if (! $accessToken ||
                ($this->expiration &&
                 $accessToken->created_at->lte(now()->subMinutes($this->expiration))) ||
                ! $this->hasValidProvider($accessToken->tokenable)) {
                return;
            }

As you can see, it does exactly what I want. However, I can't figure out how to set my own value for the attribute $expiration.

In this same file, there are some allusion to an existing configuration file, like this one: config('sanctum.guard', 'web'). Also, the class SanctumServiceProvider instanciates Guard and passes to its constructor the following value: config('sanctum.expiration'). But I don't know how/where to define this config value. Perhaps https://laravel.com/docs/8.x/configuration config(['sanctum.expiration' => '1277126']);? Could you confirm it please? (but where to put this line?)

Question

My question is: in Laravel 8 Sanctum, how could I set my own value for the variable $expiration used for Sanctum tokens check? Should I edit a configuration file and if yes, how? Should I type a configuration command in a terminal?


Solution

  • You can publish the Laravel configuration:

    php artisan vendor:publish --provider="Laravel\Sanctum\SanctumServiceProvider"
    

    See https://laravel.com/docs/8.x/sanctum#installation

    After this you are able to change all configuration options in config/sanctum.php. The configuration files in config will overwrite the vendor default configuration.