Tymon/jwt-auth
Installation
composer require tymon/jwt-auth
This service provider must be registered.
Tymon\JWTAuth\Providers\JWTAuthServiceProvider::class,
Add this to your aliases
'JWTAuth' => Tymon\JWTAuth\Facades\JWTAuth::class, 'JWTFactory' => Tymon\JWTAuth\Facades\JWTFactory::class
To publish the config settings in Laravel 5 use
php artisan vendor:publish --provider="Tymon\JWTAuth\Providers\JWTAuthServiceProvider"
Don’t forget to set a secret key in the config file!
php artisan jwt:generate
Add Middleware
'jwt.auth' => \Tymon\JWTAuth\Middleware\GetUserFromToken::class, 'jwt.refresh' => \Tymon\JWTAuth\Middleware\RefreshToken::class,
For Lumen
This service provider must be registered.
$app->register(Tymon\JWTAuth\Providers\JWTAuthServiceProvider::class);
Add Facade To Bootstrap App.php
$app->withFacades(true,[ ... 'Tymon\JWTAuth\Facades\JWTAuth' => 'JWTAuth', 'Tymon\JWTAuth\Facades\JWTFactory' => 'JWTFactory' ]);
Add Middleware To Bootstrap App.php
$app->routeMiddleware([ .... 'jwt.auth' => Tymon\JWTAuth\Middleware\GetUserFromToken::class, 'jwt.refresh' => Tymon\JWTAuth\Middleware\RefreshToken::class, ]);
Error
Unresolvable dependency resolving [Parameter #0 [ $app ]] in class Illuminate\Cache\CacheManager
Dependency Bind from
$app->bind(Illuminate\Cache\CacheManager::class, function ($app) { return new Illuminate\Cache\CacheManager($app); });
Unresolvable dependency resolving [Parameter #0 [ $app ]] in class Illuminate\Auth\AuthManager
$app->bind(Illuminate\Auth\AuthManager::class, function ($app) { return new Illuminate\Auth\AuthManager($app); });
Examples
use JWTAuth; use Tymon\JWTAuth\Exceptions\JWTException; $date=['name'=>'root','password'=>'123456',]; $token=\JWTAuth::attempt($date,['driver'=>'ios']); //dd(\JWTAuth::toUser($token)->toArray()); //dd(\JWTAuth::getPayload($token)->toArray()); try{ dd (\JWTAuth::authenticate($token)->toArray()); }catch(JWTException $e){ dd($e->getStatusCode()."--".$e->getMessage()."--line:".$e->getLine()."--".$e->getFile()); }
For Lumen
$this->validate($request, [ 'mobile' => 'required|digits:11', 'password' => 'required', ]); $mobile=$request->input('mobile'); $password=$request->input('password'); $user=User::where('mobile',$mobile)->first(); if ($user&&Hash::check($password, $user->password)){ try { $token=JWTAuth::fromUser($user);//['driver'] return response()->json(compact('token')); }catch (JWTException $e){ return $e->getStatusCode()."--".$e->getMessage()."--line:".$e->getLine()."--".$e->getFile(); } }else{ return response()->json(['error'=>'1001']); }