There are different types of API authentication systems available in the Laravel 10 application, Like Laravel passport, Laravel sanctum and of course, you can also use JWT authentication. In this JSON Web Token Authentication for Laravel 10 tutorial, we will use JWT to create this API authentication in Laravel. 

We will use the php-open-source-saver/jwt-auth package which is a fork of tymondesign/jwt-auth cause this package is not compatible with Laravel 9 and Laravel 10. So in this Laravel 10 JWT authentication tutorial, I will use this php-open-source-saver/jwt-auth package.

You know that, the JWT API authentication process is more secure than Laravel sanctum or Laravel passport. So in this tutorial, you will learn how to create a complete jwt auth laravel 10 application. I will create Login, Register, Logout, and Refresh Token APIand all of those APIs are made with POST requests. So let's start laravel 10 jwt auth tutorial:

 

Step 1: Install Laravel 10

First of all, we need to get a fresh Laravel 10 version application using the bellow command to start tymonjwt auth laravel 10.

composer create-project laravel/laravel example-app

 

Step 2: Connect Database

I am going to use the MYSQL database for this jwt auth laravel 10. So connect the database by updating.env like this:

.env

DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=YOUR_DB_NAME
DB_USERNAME=YOUR_DB_USERNAME
DB_PASSWORD=YOUR_DB_PASSWORD

 

Now run php artisan migrate command to migrate the database.

 

Read also: Laravel 10 Guzzle HTTP Client Headers With Multi-Part Example

 

Step 3: Install JWT

In this step, we will install php-open-source-saver/jwt-auth package. So open the terminal and run the below command:

composer require php-open-source-saver/jwt-auth

 

And now publish the configuration file by running this command:

php artisan vendor:publish --provider="PHPOpenSourceSaver\JWTAuth\Providers\LaravelServiceProvider"

 

Now run the below command to generate JWT secret key like:

php artisan jwt:secret

 

This command will update your .env file like this:

.env

JWT_SECRET=TIfwzvlyoyDLMTnuYvZ771DeYcv0HmJvyFgajlGezgWU0cekfY0dLGJfvoL3AkjE
JWT_ALGO=HS256

 

Step 4: Confuring API Guard

Now in this step, we have to update and set up the API authentication guard. So update the following file like that:

config/auth.php

<?php

return [

    /*
    |--------------------------------------------------------------------------
    | Authentication Defaults
    |--------------------------------------------------------------------------
    |
    | This option controls the default authentication "guard" and password
    | reset options for your application. You may change these defaults
    | as required, but they're a perfect start for most applications.
    |
    */

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

    /*
    |--------------------------------------------------------------------------
    | Authentication Guards
    |--------------------------------------------------------------------------
    |
    | Next, you may define every authentication guard for your application.
    | Of course, a great default configuration has been defined for you
    | here which uses session storage and the Eloquent user provider.
    |
    | All authentication drivers have a user provider. This defines how the
    | users are actually retrieved out of your database or other storage
    | mechanisms used by this application to persist your user's data.
    |
    | Supported: "session"
    |
    */

    'guards' => [
        'web' => [
            'driver' => 'session',
            'provider' => 'users',
        ],

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

    /*
    |--------------------------------------------------------------------------
    | User Providers
    |--------------------------------------------------------------------------
    |
    | All authentication drivers have a user provider. This defines how the
    | users are actually retrieved out of your database or other storage
    | mechanisms used by this application to persist your user's data.
    |
    | If you have multiple user tables or models you may configure multiple
    | sources which represent each model / table. These sources may then
    | be assigned to any extra authentication guards you have defined.
    |
    | Supported: "database", "eloquent"
    |
    */

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

        // 'users' => [
        //     'driver' => 'database',
        //     'table' => 'users',
        // ],
    ],

    /*
    |--------------------------------------------------------------------------
    | Resetting Passwords
    |--------------------------------------------------------------------------
    |
    | You may specify multiple password reset configurations if you have more
    | than one user table or model in the application and you want to have
    | separate password reset settings based on the specific user types.
    |
    | The expiry time is the number of minutes that each reset token will be
    | considered valid. This security feature keeps tokens short-lived so
    | they have less time to be guessed. You may change this as needed.
    |
    | The throttle setting is the number of seconds a user must wait before
    | generating more password reset tokens. This prevents the user from
    | quickly generating a very large amount of password reset tokens.
    |
    */

    'passwords' => [
        'users' => [
            'provider' => 'users',
            'table' => 'password_reset_tokens',
            'expire' => 60,
            'throttle' => 60,
        ],
    ],

    /*
    |--------------------------------------------------------------------------
    | Password Confirmation Timeout
    |--------------------------------------------------------------------------
    |
    | Here you may define the amount of seconds before a password confirmation
    | times out and the user is prompted to re-enter their password via the
    | confirmation screen. By default, the timeout lasts for three hours.
    |
    */

    'password_timeout' => 10800,

];

 

Step 5: Update User Model

Now all are set to go. Now we have to update the User model like below. So update it to create laravel jwt auth:

app\Models\User.php

<?php

namespace App\Models;

use Laravel\Sanctum\HasApiTokens;
use Illuminate\Notifications\Notifiable;
use Illuminate\Contracts\Auth\MustVerifyEmail;
use PHPOpenSourceSaver\JWTAuth\Contracts\JWTSubject;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Foundation\Auth\User as Authenticatable;

class User extends Authenticatable implements JWTSubject
{
    use HasApiTokens, HasFactory, Notifiable;

    /**
     * The attributes that are mass assignable.
     *
     * @var array<int, string>
     */
    protected $fillable = [
        'name',
        'email',
        'password',
    ];

    /**
     * The attributes that should be hidden for serialization.
     *
     * @var array<int, string>
     */
    protected $hidden = [
        'password',
        'remember_token',
    ];

    /**
     * The attributes that should be cast.
     *
     * @var array<string, string>
     */
    protected $casts = [
        'email_verified_at' => 'datetime',
    ];

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

 

Step 6: Create Route

Here, we need to add routes to set laravel generate jwt token and laravel 10 jwt authentication tutorial. So update the api routes file like this:

routes/api.php

<?php

use Illuminate\Support\Facades\Route;
use App\Http\Controllers\API\AuthController;

Route::controller(AuthController::class)->group(function () {
    Route::post('login', 'login');
    Route::post('register', 'register');
    Route::post('logout', 'logout');
    Route::post('refresh', 'refresh');
});

 

Step 7: Create Controller

Now we have to create AuthController to complete our JWT authentication with a refresh token in Laravel 10. So run the below command to create a controller:

php artisan make:controller API/AuthController

 

Now update this controller like this:

app/Http/Controllers/API/AuthController.php

<?php

namespace App\Http\Controllers\API;

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

class AuthController extends Controller
{
    public function __construct()
    {
        $this->middleware('auth:api', ['except' => ['login', 'register']]);
    }

    public function login(Request $request)
    {
        $request->validate([
            'email' => 'required|string|email',
            'password' => 'required|string',
        ]);
        $credentials = $request->only('email', 'password');
        $token = Auth::attempt($credentials);
        
        if (!$token) {
            return response()->json([
                'message' => 'Unauthorized',
            ], 401);
        }

        $user = Auth::user();
        return response()->json([
            'user' => $user,
            'authorization' => [
                'token' => $token,
                'type' => 'bearer',
            ]
        ]);
    }

    public function register(Request $request)
    {
        $request->validate([
            'name' => 'required|string|max:255',
            'email' => 'required|string|email|max:255|unique:users',
            'password' => 'required|string|min:6',
        ]);

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

        return response()->json([
            'message' => 'User created successfully',
            'user' => $user
        ]);
    }

    public function logout()
    {
        Auth::logout();
        return response()->json([
            'message' => 'Successfully logged out',
        ]);
    }

    public function refresh()
    {
        return response()->json([
            'user' => Auth::user(),
            'authorisation' => [
                'token' => Auth::refresh(),
                'type' => 'bearer',
            ]
        ]);
    }
}

 

Now if you start your server by running php artisan serve and test all API via Postman like this:

REGISTER API
http://127.0.0.1:8000/api/register

 

And now see the Postman output:

laravel-10-jwt

LOGIN API
http://127.0.0.1:8000/api/login

 

And look at that Postman output:

laravel-10-jwt-tutorial

LOGOUT API
http://127.0.0.1:8000/api/logout

 

Now see the Postman output. Don't forget to add a bearer token with your headers.

laravel-10-jwt-authentication-tutorial

REFRESH TOKEN
http://127.0.0.1:8000/api/refresh

 

Now see the Postman output. Don't forget to add the bearer token with your headers.

refresh-token-laravel-jwt

Read also: Laravel 10 Guzzle HTTP Client POST Request Example

 

Conclusion

After completing this laravel 10 jwt tutorial, now you know how to use tymonjwt auth laravel 10. Hope after following this laravel 10 jwt authentication tutorial, you own now be able to set laravel generate jwt token. Hope this jwt auth laravel 10 tutorial will help you.

Category : #laravel

Tags : #laravel , #laravel api