JWT + Laravel 8 : Autenticación con JWT en laravel

1. Create project / Crear proyecto

composer create-project --prefer-dist laravel/laravel proyecto-jwt

2. Migrate

php artisan migrate

3. Intall JWT / Instalar JWT

composer require tymon/jwt-auth:dev-develop --prefer-source

3. Add JWT / Agregar JWT en Providers & Aliases

Add line in Provider / Agregar linea en el Proveedor config/app.php

'providers' => [

        /*  ...  */

        Tymon\JWTAuth\Providers\LaravelServiceProvider::class,
],


'aliases' => [

        /*  ...  */

        'JWTAuth' => Tymon\JWTAuth\Facades\JWTAuth::class,
        'JWTFactory' => Tymon\JWTAuth\Facades\JWTFactory::class,
],

4. Run JWT

php artisan jwt:secret

// res
// jwt-auth secret [XjaoZd3NYH3n3rkksEnu6geNJyDG6NFM5PKQJyvjGClGZQNAi6FrxrT6hmEbw3JF] set successfully.

5. Create Middleware / Crear Middleware

Create a middleware for JWT / Crearemos migración para JWT

php artisan make:middleware JwtMiddleware

app/Http/Middleware/JwtMiddleware.php

<?php

namespace App\Http\Middleware;

use Closure;
use JWTAuth;
use Exception;
use Tymon\JWTAuth\Http\Middleware\BaseMiddleware;

class JwtMiddleware extends BaseMiddleware
{

    public function handle($request, Closure $next)
    {
        try {
            $user = JWTAuth::parseToken()->authenticate();
        } catch (Exception $e) {
            if ($e instanceof \Tymon\JWTAuth\Exceptions\TokenInvalidException){
                return response()->json(['status' => 'Token is Invalid']);
            }else if ($e instanceof \Tymon\JWTAuth\Exceptions\TokenExpiredException){
                return response()->json(['status' => 'Token is Expired']);
            }else{
                return response()->json(['status' => 'Authorization Token not found']);
            }
        }
        return $next($request);
    }
}

6. Add route middleware / Agregar Middleware de ruta

app/Http/Kernel.php

<?php

namespace App\Http;

use Illuminate\Foundation\Http\Kernel as HttpKernel;

class Kernel extends HttpKernel
{
    /* ... */

    /**
     * The application's route middleware.
     *
     * These middleware may be assigned to groups or used individually.
     *
     * @var array
     */
    protected $routeMiddleware = [
        /* ... */
        'jwt.verify' => \App\Http\Middleware\JwtMiddleware::class,
    ];
}

7. Model / Modelo User

app/Models/User.php

<?php

namespace App\Models;

// ... //
use Tymon\JWTAuth\Contracts\JWTSubject;

class User extends Authenticatable implements JWTSubject
{
   
  	// ... //
    public function getJWTIdentifier()
    {
    	return $this->getKey();
    }

    public function getJWTCustomClaims()
    {
    	return [];
    }

}

8. Create controller / Crear controlador

php artisan make:controller UserController
<?php

namespace App\Http\Controllers;

use App\Models\User;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\Validator;
use JWTAuth;
use Tymon\JWTAuth\Exceptions\JWTException;
use Log;

class UserController extends Controller
{
    public function authenticate(Request $request)
    {
      $credentials = $request->only('email', 'password');
      try {
          if (! $token = JWTAuth::attempt($credentials)) {
              return response()->json(['error' => 'invalid_credentials'], 400);
          }
      } catch (JWTException $e) {
          return response()->json(['error' => 'could_not_create_token'], 500);
      }
      return response()->json(compact('token'));
    }

    public function getAuthenticatedUser()
    {
        try {
          if (!$user = JWTAuth::parseToken()->authenticate()) {
                  return response()->json(['user_not_found'], 404);
          }
        } catch (Tymon\JWTAuth\Exceptions\TokenExpiredException $e) {
                return response()->json(['token_expired'], $e->getStatusCode());
        } catch (Tymon\JWTAuth\Exceptions\TokenInvalidException $e) {
                return response()->json(['token_invalid'], $e->getStatusCode());
        } catch (Tymon\JWTAuth\Exceptions\JWTException $e) {
                return response()->json(['token_absent'], $e->getStatusCode());
        }
        return response()->json(compact('user'));
    }


    public function register(Request $request)
    {

        Log::info($request);
        $validator = Validator::make($request->all(), [
            'name' => 'required|string|max:255',
            'email' => 'required|string|email|max:255|unique:users',
            'password' => 'required|string|min:6|confirmed',
        ]);

        if($validator->fails()){
                return response()->json($validator->errors()->toJson(),400);
        }

        $user = User::create([
            'name' => $request->get('name'),
            'email' => $request->get('email'),
            'password' => Hash::make($request->get('password')),
        ]);

        $token = JWTAuth::fromUser($user);

        return response()->json(compact('user','token'),201);
    }
}

9. Create Router / Crear Ruta

Route::post('register', 'App\Http\Controllers\[email protected]');
Route::post('login', 'App\Http\Controllers\[email protected]');

Route::group(['middleware' => ['jwt.verify']], function() {

    Route::post('user','App\Http\Controllers\[email protected]');

});

10. Run project

php artisan serve

Test Postman

Register

http://localhost:8000/api/register
{
    "name" : "artyom developer",
    "password" : "tutofox123",
    "password_confirmation" : "tutofox123",
    "email" : "[email protected]"
}

Login

http://localhost:8000/api/login
{
    "email" : "[email protected]",
    "password" : "tutofox123"
}

User

http://localhost:8000/api/user
Authorization: Bearer <TOKEN>

Deja una respuesta

Tu dirección de correo electrónico no será publicada. Los campos obligatorios están marcados con *