0% found this document useful (0 votes)
121 views

Jwt-Auth: Pacote: Tymon/Jwt-Auth Github: Documentação: 1. Instalar O Pacote

This document provides instructions for setting up JWT authentication with the tymon/jwt-auth package in a Laravel application. It describes: 1. Installing the tymon/jwt-auth package 2. Registering the JWT auth service provider 3. Generating a JWT secret key 4. Creating an AuthController to generate and validate tokens
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
121 views

Jwt-Auth: Pacote: Tymon/Jwt-Auth Github: Documentação: 1. Instalar O Pacote

This document provides instructions for setting up JWT authentication with the tymon/jwt-auth package in a Laravel application. It describes: 1. Installing the tymon/jwt-auth package 2. Registering the JWT auth service provider 3. Generating a JWT secret key 4. Creating an AuthController to generate and validate tokens
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 3

JWT-Auth

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

2. Registrar provider em config/app.php


'providers' => [
...
Tymon\JWTAuth\Providers\LaravelServiceProvider::class,
]

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

6. Criar rota e controlador para geração de tokens


php artisan make:controller API\AuthController

use JWTAuth;
use Tymon\JWTAuth\Exceptions\JWTException;

class AuthController extends Controller


{
public function authenticate(Request $request){

        $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 ));
    }
}

7. Atualizar modelo de usuário

namespace App;

use Tymon\JWTAuth\Contracts\JWTSubject;
use Illuminate\Notifications\Notifiable;
use Illuminate\Foundation\Auth\User as Authenticatable;

class User extends Authenticatable implements JWTSubject


{
use Notifiable;

// Rest omitted for brevity

/**
* 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 [];
}
}

8. Criar Middleware e registra-lo em app\Http\Kernel.php


php artisan make:middleware JwtMiddleware 

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,
];

You might also like