Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using Laravel 8 with Sanctum hasapitokens to login with a remember me option

So Im building a SPA with Vue 3, Laravel 8 and using sanctum (hasapitokens) to handle the user login and I could not find the duration of the session that the token is valid as I wanted to use this in combination with a remember me option when a user signs in. Is this possible or is the use of these tokens a bad example to handle the authentication of users?

like image 382
user759235 Avatar asked Oct 27 '25 01:10

user759235


1 Answers

It's usually done via cookies, but when dealing with sanctum authentication, it's a little tricky.

I thought, why don't I just make the sanctum token expiration date longer when login happens with the "remember me" option? But apparently you can't make different tokens with different expiration dates with sanctum, so here an alternative.


A. With sanctum token's abilities:

When creating the user's token, add to the abilities list a "remember" ability.

$user->createToken('auth_token_name', ['remember']);

Then in the App/Providers/AppServiceProvider.php file in the boot() method add

Sanctum::authenticateAccessTokensUsing(function (PersonalAccessToken $token, $isValid) {
        if($isValid) return true;
        return $token->can('remember') && $token->created_at->gt(now()->subYears(5));
    });

Usually the expiration duration of Laravel "remember cookie" is five years. Here you are free to change this to any duration.


B. Add an expiration column to the tokens table (TL;DR)

I haven't tested this one myself because it's a long way, but should offer you an alternative incase you don't want to mess with the token's abilities. First, you need to modify the sanctum migration to include an expiration column (as in here). Then you need to override the PersonalAccessToken Model (as in here) to have in the fillable property the expiration column. Then you can add to the boot() method in the AppServiceProvider

Sanctum::authenticateAccessTokensUsing(function (PersonalAccessToken $token, $isValid) {
    return $isValid ?: $token->expiration->gt(now());
});

The only problem is that you need to set expiration date, so either fetch the newly created token from the database and modify that, or override the HasApiToken::createToken function in the User model to use expiration parameter.

like image 150
Chase Codex Avatar answered Oct 31 '25 05:10

Chase Codex



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!