This was released before Laravel Sanctum. I would recommend using Laravel Sanctum instead.
Adds the ability to use multiple tokens for the auth:api middleware. Useful if you want to allow a user to be logged in to your e.g. SPA, iOS app and android app at the same time. The default token driver only allows one token per user.
It is possible to end up with a large table when using multiple tokens per user. Therefor we set an expiration date on the tokens. If possible, you should add the PurgeExpiredApiTokensJob
to your Schedule as the Step 6 describes. If not, you should somehow take care of the expired tokens.
You may take a look at the example app multiple-tokens-auth-testapp.
-
Install the package with composer:
composer require livijn/multiple-tokens-auth
-
Publish the
multiple-tokens-auth.php
config & migrations:php artisan vendor:publish --provider="Livijn\MultipleTokensAuth\MultipleTokensAuthServiceProvider"
By default, the migration is shipped with the field
user_id
that hasunsignedBigInteger
. This needs to be manually changed if you useuuid
in your User model. -
Run the migrations:
php artisan migrate
-
Set the api guard driver to
multiple-tokens
in the fileconfig/auth.php
:'guards' => [ // ... 'api' => [ 'driver' => 'multiple-tokens', // <- Change this FROM token TO multiple-tokens // ... ], ],
-
Add the
HasApiTokens
trait to your User model.class User extends Authenticatable { use Notifiable, HasApiTokens; // ... }
-
(Optional) Add the
PurgeExpiredApiTokensJob
to your Schedule atConsole/Kernel.php
.protected function schedule(Schedule $schedule) { $schedule->job(PurgeExpiredApiTokensJob::class)->dailyAt('01:00'); }
You can use this the same way as you would use the default Laravel token based API authorization. This package also supports hashing.
When a user logs in, you should create a new api token by using the generateApiToken
method.
$user = User::first();
$token = $user->generateApiToken(); // returns ltBKMC8zwnshLcrVh9W07IGuifysDqkyWRt6Z5szYJOrh1mnNPValkAtETj0vtPJdsfDQa4E3Yx0N3QU
When you want to log out a user, you can use the logout
method on the Auth facade. This will delete the token that was used for the current request.
auth()->logout();
// or
Auth::logout();
To delete all tokens connected to a user, use the purgeApiTokens
method.
$user = User::first();
$user->purgeApiTokens();
Run the tests with:
vendor/bin/phpunit
The MIT License (MIT). Please see License File for more information.