multiple-tokens-auth
multiple-tokens-auth copied to clipboard
Adds the ability to use multiple tokens for the auth:api middleware.
Important
This was released before Laravel Sanctum. I would recommend using Laravel Sanctum instead.
multiple-tokens-auth
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
-
Install the package with composer:
composer require livijn/multiple-tokens-auth -
Publish the
multiple-tokens-auth.phpconfig & migrations:php artisan vendor:publish --provider="Livijn\MultipleTokensAuth\MultipleTokensAuthServiceProvider"By default, the migration is shipped with the field
user_idthat hasunsignedBigInteger. This needs to be manually changed if you useuuidin your User model. -
Run the migrations:
php artisan migrate -
Set the api guard driver to
multiple-tokensin the fileconfig/auth.php:'guards' => [ // ... 'api' => [ 'driver' => 'multiple-tokens', // <- Change this FROM token TO multiple-tokens // ... ], ], -
Add the
HasApiTokenstrait to your User model.class User extends Authenticatable { use Notifiable, HasApiTokens; // ... } -
(Optional) Add the
PurgeExpiredApiTokensJobto your Schedule atConsole/Kernel.php.protected function schedule(Schedule $schedule) { $schedule->job(PurgeExpiredApiTokensJob::class)->dailyAt('01:00'); }
Usage
You can use this the same way as you would use the default Laravel token based API authorization. This package also supports hashing.
Sign in
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
Sign out
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();
Purging tokens
To delete all tokens connected to a user, use the purgeApiTokens method.
$user = User::first();
$user->purgeApiTokens();
Testing
Run the tests with:
vendor/bin/phpunit
Credits
License
The MIT License (MIT). Please see License File for more information.