Jwt-Auth: Pacote: Tymon/Jwt-Auth Github: Documentação: 1. Instalar O Pacote
Jwt-Auth: Pacote: Tymon/Jwt-Auth Github: Documentação: 1. Instalar O Pacote
Pacote: tymon/jwt-auth
GitHub: https://github.com/tymondesigns/jwt-auth
Documentação: https://jwt-auth.readthedocs.io/en/develop/
1. Instalar o pacote:
composer require tymon/jwt-auth:dev-develop –-prefer-source
3. Registrar Aliases
'JWTAuth' => Tymon\JWTAuth\Facades\JWTAuth::class,
'JWTFactory' => Tymon\JWTAuth\Facades\JWTFactory::class,
4. Publicar configurações
php artisan vendor:publish --provider="Tymon\JWTAuth\Providers\LaravelServiceProvider"
5. Gerar a chave
php artisan jwt:secret
use JWTAuth;
use Tymon\JWTAuth\Exceptions\JWTException;
$errorReportResponse = null;
$authResponse = null;
$credentials = $request->only('email', 'password');
try {
if (! $token = JWTAuth::attempt($credentials)) {
$errorReportResponse[] = (object)array(
'code' => 'INVALID_CREDENTIALS',
'message' => 'Suas credenciais são inválidas'
);
}else{
$user = new \App\Http\Resources\API\v1\UserResource( \Auth::user());
$authResponse = array(
'token' => $token,
'user' => $user,
);
}
} catch (JWTException $e) {
$errorReportResponse[] = (object)array(
'code' => 'ERROR',
'message' => 'Erro interno',
);
}
return response(array(
'errorReport' =>$errorReportResponse,
'user' => isset($user) ? $user : null,
'auth' =>(object)$authResponse
),
( isset($errorReportResponse) ? 200 : 401 ));
}
}
namespace App;
use Tymon\JWTAuth\Contracts\JWTSubject;
use Illuminate\Notifications\Notifiable;
use Illuminate\Foundation\Auth\User as Authenticatable;
/**
* Get the identifier that will be stored in the subject claim of the JWT.
*
* @return mixed
*/
public function getJWTIdentifier()
{
return $this->getKey();
}
/**
* Return a key value array, containing any custom claims to be added to the JWT.
*
* @return array
*/
public function getJWTCustomClaims()
{
return [];
}
}
use JWTAuth;
use Exception;
class JwtMiddleware{
public function handle($request, Closure $next){
try {
$user = JWTAuth::parseToken()->authenticate();
} catch (Exception $e) {
if ($e instanceof \Tymon\JWTAuth\Exceptions\TokenInvalidException){
return response()->json(
array(
'errorReport' => (object)array(
'code' => 'TOKEN_INVALID',
'message'=> 'Token inválido.',
)
)
);
}else if ($e instanceof \Tymon\JWTAuth\Exceptions\TokenExpiredException){
return response()->json(
array(
'errorReport' => (object)array(
'code' => 'TOKEN_EXPIRED',
'message'=> 'Seu token expirou.',
)
)
);
}else{
return response()->json(
array(
'errorReport' => (object)array(
'code' => 'TOKEN_MISSING',
'message'=> 'Não foi encontrado token de autorização',
)
)
);
}
}
return $next($request);
}
}
protected $routeMiddleware = [
...
'JwtMiddleware' => \App\Http\Middleware\JwtMiddleware::class,
];