Blog Mauricio Alpizar Lumen/Laravel Configurar JWT en Lumen con “tymon/jwt-auth”

Configurar JWT en Lumen con “tymon/jwt-auth”

Instalación

Instalación Lumen via composer.


composer create-project --prefer-dist laravel/lumen 9.x lumen-jwt

Agregue en el config folder (crear el directorio en raíz si no lo tiene) y agregue el archivo auth.php dentro de la carpeta de configuración, config/auth.php y agregue el código a continuación en el archivo auth.php

<?php

return [
    'defaults' => [
        'guard' => 'api',
        'passwords' => 'users',
    ],

    'guards' => [
        'api' => [
            'driver' => 'jwt',
            'provider' => 'users',
        ],
    ],

    'providers' => [
        'users' => [
            'driver' => 'eloquent',
            'model' => \App\Models\User::class
        ]
    ]
];

Instalación de jwt-auth via composer

composer require tymon/jwt-auth:*

Cambios en el Bootstrap file

Agregue el siguiente fragmento de código al archivo bootstrap/app.php en el directorio raíz de la siguiente manera:

// Uncomment this line

$app->withFacades();

$app->withEloquent();

Then uncomment the auth middleware 

$app->routeMiddleware([
    'auth' => App\Http\Middleware\Authenticate::class,
]);

$app->register(App\Providers\AuthServiceProvider::class);

// Add this line in the same file:

$app->register(Tymon\JWTAuth\Providers\LumenServiceProvider::class);

Generar el secret key

Ejecute en consola:

Esto actualiza el archivo .env con lo siguiente:

JWT_SECRET=secret_jwt_string_key

Es la clave que se utilizará para firmar sus tokens.

Database Connection

Inside the .env file.

DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=db_name
DB_USERNAME=root
DB_PASSWORD=

Crear la Migracion

Ejecute esto para la migración de la tabla de usuarios a continuación

php artisan make:migration create_users_table

Y reemplácelo con el siguiente código en

database\migrations*_create_users_table.php

<?php

use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;

class CreateUsersTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('users', function (Blueprint $table) {
            $table->id();
            $table->string('name');
            $table->string('email')->unique();
            $table->timestamp('email_verified_at')->nullable();
            $table->string('password');
            $table->rememberToken();
            $table->timestamps();
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::dropIfExists('users');
    }
}

Migrar la base de datos

Cree el seeder de base de datos para un usuario ejecutando la siguiente instrucción:

php artisan make:seeder UserTableSeeder

Y reemplácelo con el siguiente código en

database\seeders\UserTableSeeder.php

<?php

namespace Database\Seeders;

use App\Models\User;
use Illuminate\Database\Seeder;
use Illuminate\Support\Facades\Hash;


class UserTableSeeder extends Seeder
{
    /**
     * Run the database seeds.
     *
     * @return void
     */
    public function run()
    {
        $users = User::create([
            'name' => 'Md.Meherul Islam', 
            'email' => 'meherul@gmail.com',
            'password' => Hash::make('12345678')
        ]);
    }
}

Luego ejecute el comando que fluye para insertar datos en su base de datos

php artisan db:seed --class=UserTableSeeder


Ahora cree un archivo AuthController.php en app\Http\Controllers\AuthController.php


<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use  App\Models\User;

class AuthController extends Controller
{


    public function __construct()
    {
        $this->middleware('auth:api', ['except' => ['login', 'refresh', 'logout']]);
    }
    /**
     * Get a JWT via given credentials.
     *
     * @param  Request  $request
     * @return Response
     */
    public function login(Request $request)
    {

        $this->validate($request, [
            'email' => 'required|string',
            'password' => 'required|string',
        ]);

        $credentials = $request->only(['email', 'password']);

        if (! $token = Auth::attempt($credentials)) {
            return response()->json(['message' => 'Unauthorized'], 401);
        }

        return $this->respondWithToken($token);
    }

     /**
     * Get the authenticated User.
     *
     * @return \Illuminate\Http\JsonResponse
     */
    public function me()
    {
        return response()->json(auth()->user());
    }

    /**
     * Log the user out (Invalidate the token).
     *
     * @return \Illuminate\Http\JsonResponse
     */
    public function logout()
    {
        auth()->logout();

        return response()->json(['message' => 'Successfully logged out']);
    }

    /**
     * Refresh a token.
     *
     * @return \Illuminate\Http\JsonResponse
     */
    public function refresh()
    {
        return $this->respondWithToken(auth()->refresh());
    }

    /**
     * Get the token array structure.
     *
     * @param  string $token
     *
     * @return \Illuminate\Http\JsonResponse
     */
    protected function respondWithToken($token)
    {
        return response()->json([
            'access_token' => $token,
            'token_type' => 'bearer',
            'user' => auth()->user(),
            'expires_in' => auth()->factory()->getTTL() * 60 * 24
        ]);
    }
}


Ahora reemplace el código del modelo de usuario en app\Models\User.php con el siguiente código.


<?php

namespace App\Models;

use Illuminate\Auth\Authenticatable;
use Laravel\Lumen\Auth\Authorizable;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Contracts\Auth\Authenticatable as AuthenticatableContract;
use Illuminate\Contracts\Auth\Access\Authorizable as AuthorizableContract;

//this is new
use Tymon\JWTAuth\Contracts\JWTSubject;

class User extends Model implements AuthenticatableContract, AuthorizableContract, JWTSubject 
{
    use Authenticatable, Authorizable;

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


Cambie los archivos de ruta a las rutas \web.php con el siguiente código:


<?php

/** @var \Laravel\Lumen\Routing\Router $router */

/*
|--------------------------------------------------------------------------
| Application Routes
|--------------------------------------------------------------------------
|
| Here is where you can register all of the routes for an application.
| It is a breeze. Simply tell Lumen the URIs it should respond to
| and give it the Closure to call when that URI is requested.
|
*/




$router->get('/', function () use ($router) {
    echo "<center> Welcome </center>";
});

$router->get('/version', function () use ($router) {
    return $router->app->version();
});

Route::group([

    'prefix' => 'api'

], function ($router) {
    Route::post('login', 'AuthController@login');
    Route::post('logout', 'AuthController@logout');
    Route::post('refresh', 'AuthController@refresh');
    Route::post('user-profile', 'AuthController@me');

});

Pruebe la API de autenticación Lumen JWT con Postman


Ahora correo el servidor con el siguiente comando en consola:

php -S localhost:8000 -t public

Hemos creado una API REST segura utilizando la autenticación JWT. Para que el proceso de prueba sea fácil y sutil, confiaremos en Postman.

Autenticacion de APIs para Login, User Profile, Token Refresh and Logout.

Metodos de Endpoint PostMan

  • POST localhost:8000/api/login
  • POST localhost:8000/api/user-profile
  • POST localhost:8000/api/refresh
  • POST localhost:8000/api//logout

Related Post