composer require aikrof/jwt-auth
Add the service provider to the providers
array in the config/app.php
config file:
'providers' => [ ... Aikrof\JwtAuth\Providers\JwtServiceProvider::class, ... ],
php artisan vendor:publish --provider="Aikrof\JwtAuth\Providers\JwtServiceProvider"
This command will be create config/jwt.php
file with basics configure.
Create table where will be stored invalid tokens.
php artisan migrate
php artisan create:secret
This command will create JWT_SECRET_KEY and JWT_REFRESH_KEY in your .env
file.
Inside the config/auth.php
file change:
'defaults' => [ 'guard' => 'api', 'passwords' => 'users', ], ... 'guards' => [ ... 'api' => [ 'driver' => 'jwt', 'provider' => 'users', ], ],
Set api
guard as the default and add jwt
driver to api
guard
Add trait
to your User model:
1)Implement the Aikrof\JwtAuth\JwtCreator
2)Then add trait use JwtCreator
namespace App; use Illuminate\Notifications\Notifiable; use Illuminate\Contracts\Auth\MustVerifyEmail; use Illuminate\Foundation\Auth\User as Authenticatable; use Aikrof\JwtAuth\JwtCreator; class User extends Authenticatable { use JwtCreator, Notifiable; .... }
By default token time to live (ttl
) is 1 week,
you can change ttl
in config/jwt.php
file or
when create new token:
Auth::user()->setTtl(2);
Example sets token time to live by 2 minutes.
setTtl()
-takes parameter in minutes.
By default refresh token time to live is token ttl * 2
,
you can change refreshTtl
in config/jwt.php
file or
when create new token:
Auth::user()->setRefreshTtl(4);
Example sets token time to live by 4 minutes.
setRefreshTtl()
-takes parameter in minutes.
Auth::token();
Or with setTtl() or setRefreshTtl()
Auth::user()->setTtl(2)->setRefreshTtl()->token();
Will be returned array with this fields:
[ 'token' => '...', 'refresh' => '...' ]
Auth::user()->getTtl();
To get token time to live in UNIX timestamp
Auth::user()->getExpTtl();
Auth::user()->getRefreshTtl();
To get refresh token time to live in UNIX timestamp
Auth::user()->getRefreshExpTtl();
Log the user out - which will invalidate the current token and unset the authenticated user.
Auth::logout();
Refresh a token, which invalidates the current one and returned new token and refresh token.
Auth::refresh();
If jwt token was invalid or have invalid data then will be returned null
.