DEV Community πŸ‘©β€πŸ’»πŸ‘¨β€πŸ’»

Wendel Lopes
Wendel Lopes

Posted on

Laravel and JWT Authentication with custom model

  • Before we start, this is the first article i write in english, so apologize for any mistakes.

In this article, i will show you how to implement JWT authentication (using tymon/jwt-auth package) in a Laravel api, using a different model than the default (Users). At the end, a link to the repository will be available with the content of this article.

Portuguese version: https://dev.to/wenlopes/laravel-8-e-autenticacao-jwt-tymon-jwt-auth-com-model-customizada-2l7k

So let's go!

Installation

Run this command to install the package

composer require tymon/jwt-auth
Enter fullscreen mode Exit fullscreen mode

Publish the lib config file in your config folder, with the command

php artisan vendor:publishβ€Š-β€Šprovider="Tymon\JWTAuth\Providers\LaravelServiceProvider"
Enter fullscreen mode Exit fullscreen mode

Finally, let's generate the JWT secret, running the command (This command will add JWT_SECRET env in your .env file)

php artisan jwt:secret
Enter fullscreen mode Exit fullscreen mode

If you have questions about this step, this is the official link to package documentation

Model configuration

Now it's time to change our default model. For our example, let's use a Model called Employee.

For this, we gonna make a migration to create a table in our database, with same name of the Model.

php artisan make:migration create_employee_table --create=employee
Enter fullscreen mode Exit fullscreen mode

Our employee migration will have the same user migration structure that comes with the Laravel installation, but it difference will be a new column called "job_title".
Feel free to add new columns, but keep the "email" and "password" columns.

Schema::create('employee', function (Blueprint $table) {
    $table->id();
    $table->string('name');
    $table->string('email')->unique();
    $table->string('password');
    $table->string('job_title');
    $table->timestamps();
});
Enter fullscreen mode Exit fullscreen mode

Remove user migration and run

php artisan migrate
Enter fullscreen mode Exit fullscreen mode

Create the Employee model

php artisan make:model Employee
Enter fullscreen mode Exit fullscreen mode

Important: In Employee model, you may need to add the $table variable, because when we create a test user in database (a little later in this article), Laravel will try to find the table name in plural, and it will cause error. If you already created the table in plural (employees), ignore this step.

protected $table = 'employee';
Enter fullscreen mode Exit fullscreen mode

The next step is to implement JWTSubject and extends Authenticatable class (Laravel) in our Model Employee. Finally, this will be our model content.

Very well, its time to configure our authentication provider. For that, you must access the config/auth.php file and add the 'employess' index in 'providers' array, containing the driver (for this example, we are using Eloquent) and its Model (employee)

image

Now let's set the "api" guard as our application default. In the same file, access the "defaults" array and set the default guard to "api"

image

We have finished our provider configuration and this should be the final content of config/auth.php.

Creating Controller and Route

It's time to create an auth controller to test our implementation

Create an controller called AuthController, with same content of this link (official documentation from the package) and create a route in your routes/api.php file

use App\Http\Controllers\AuthController;

Route::post('auth/login', [AuthController::class, 'login'])->name('auth.login');
Enter fullscreen mode Exit fullscreen mode

To test our endpoint, lets create an employee in our database and use this data to authenticate

In the DatabaseSeeder file, insert this content in the run method

\App\Models\Employee::create([
    'name' => 'UsuΓ‘rio de teste',
    'email' => 'usuario@teste.com.br',
    'password' => bcrypt( 'senha123' ),
    'job_title' => 'Gerente administrativo'
]);
Enter fullscreen mode Exit fullscreen mode

And run this command:

php artisan db:seed
Enter fullscreen mode Exit fullscreen mode

Finally, use an API client (Postman, Insomnia...) and consume the api/auth/login login route, passing the email and password defined in the seeder. If everything work's fine, the result will be something like this:

image

So it's done! Your authentication with an custom model is working.

You can find the repository with this implementation through this link. In the repository, i'm using Docker as infra, with Nginx, Mysql and Laravel in version 8. Also, i implemented the pattern Strategy to return failed authentication messages and expired token response (in this case, a new valid token is returned).

So, that's all. If you have any questions, please comment and i will respond. Thank's for your attention.

Top comments (0)

🌚 Browsing with dark mode makes you a better developer.

It's a scientific fact.