Type in CLI
composer require tymon/jwt-auth
In Providers array add
Tymon\JWTAuth\Providers\LaravelServiceProvider::class
In Aliases array add
'JWTAuth'=>Tymon\JWTAuth\Facades\JWTAuth::class (optional)
Type in CLI
php artisan vendor:publish "Tymon\JWTAuth\Providers\LaravelServiceProvider::class"
Then a jwt.php file should be found in config directory
php artisan jwt:secret to generate a secret key
Add use Tymon\JWTAuth\Contracts\JWTSubject
Make sure the User class implements the JWTSubject class then add the following methods:
public function getJWTIdentfier()
{
return $this->getKey();
}
public function getJWTCustomClaims()
{
return [];
}
use Tymon\JWTAuth\Exceptions\JWTException
public function login(Request $request)
{
// Some input validation logic here
$credentials = $request->only(['email','password']);
try {
if(!$token = auth()->attempt($credentials)) {
return response()->json(['error'=>'Invalid email or password.'], 401);
}
} catch(JWTException $e) {
return response()->json(['error'=> $e->getMessage()], 500);
}
return response()->json(['token'=> $token], 200);
// You can add redirect logic in here just make sure to save the token
}
'jwt.auth' => \Tymon\JWTAuth\Middleware\GetUserFromToken::class
'jwt.refresh' => \Tymon\JWTAuth\Middleware\RefreshToken::class