<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0" xmlns:atom="http://www.w3.org/2005/Atom" xmlns:dc="http://purl.org/dc/elements/1.1/">
  <channel>
    <title>DEV Community: Zaiid Moumni</title>
    <description>The latest articles on DEV Community by Zaiid Moumni (@zaiidmo).</description>
    <link>https://dev.to/zaiidmo</link>
    <image>
      <url>https://media2.dev.to/dynamic/image/width=90,height=90,fit=cover,gravity=auto,format=auto/https:%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Fuser%2Fprofile_image%2F1437929%2F8686d96a-9acc-48a1-8c3d-0a6c13cd7e13.jpeg</url>
      <title>DEV Community: Zaiid Moumni</title>
      <link>https://dev.to/zaiidmo</link>
    </image>
    <atom:link rel="self" type="application/rss+xml" href="https://dev.to/feed/zaiidmo"/>
    <language>en</language>
    <item>
      <title>Laravel 10 - JWT Authentication API</title>
      <dc:creator>Zaiid Moumni</dc:creator>
      <pubDate>Thu, 23 May 2024 21:03:21 +0000</pubDate>
      <link>https://dev.to/zaiidmo/laravel-10-jwt-authentication-api-2k50</link>
      <guid>https://dev.to/zaiidmo/laravel-10-jwt-authentication-api-2k50</guid>
      <description>&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fy3aa5pkv600e2h3pj00w.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fy3aa5pkv600e2h3pj00w.png" alt="Image description"&gt;&lt;/a&gt;In a Laravel 10 application, there are various API authentication systems available, such as Laravel Passport, Laravel Sanctum, and JWT authentication. This tutorial will guide you through creating API authentication in Laravel 10 using JSON Web Tokens (JWT).&lt;/p&gt;

&lt;p&gt;For this tutorial, we will use the &lt;strong&gt;php-open-source-saver/jwt-auth ** package, which is a fork of **tymondesigns/jwt-auth&lt;/strong&gt; . The original package is not compatible with Laravel 9 and Laravel 10, making the forked version necessary for our purposes.&lt;/p&gt;

&lt;p&gt;JWT API authentication is more secure compared to Laravel Sanctum or Laravel Passport. In this tutorial, you will learn how to create a complete JWT-authenticated Laravel 10 application. We will cover the creation of Login, Register, Logout, and Refresh Token APIs, all implemented with POST requests. Let’s begin our Laravel 10 JWT authentication tutorial:&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;STEP 1: INSTALL LARAVEL PROJECT&lt;/strong&gt;&lt;br&gt;
First of all, we need to get a fresh Laravel 10 version application using the bellow command to start tymonjwt auth laravel 10.&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;

composer create-project laravel/laravel Auth 


&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;&lt;strong&gt;STEP 2: CONNECT YOUR DATABASE&lt;/strong&gt;&lt;br&gt;
I am going to use the MYSQL database for this jwt auth laravel 10. So connect the database by updating.env like this:&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;

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


&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;Now run &lt;strong&gt;php artisan migrate&lt;/strong&gt; command to migrate the database.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;STEP 3: INSTALL JSON WEB TOKEN(JWT)&lt;/strong&gt;&lt;br&gt;
In this step, we will install &lt;strong&gt;php-open-source-saver/jwt-auth&lt;/strong&gt; package. So open the terminal and run the below command:&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;

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


&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;And now publish the configuration file by running this command:&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;

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


&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;Now run the below command to generate JWT secret key like:&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;

php artisan jwt:secret


&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;This command will update your .env file like this:&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;

JWT_SECRET=TIfwzvlyoyDLMTnuYvZ771DeYcv0HmJvyFgajlGezgWU0cekfY0dLGJfvoL3AkjE
JWT_ALGO=HS256


&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;&lt;strong&gt;STEP 4: CONFIGURING API GUARD&lt;/strong&gt;&lt;br&gt;
Now in this step, we have to update and set up the API authentication guard. So update the following file like that:&lt;br&gt;
&lt;strong&gt;config/auth.php&lt;/strong&gt;&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;

&amp;lt;?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' =&amp;gt; [
        'guard' =&amp;gt; 'api',
        'passwords' =&amp;gt; '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' =&amp;gt; [
        'web' =&amp;gt; [
            'driver' =&amp;gt; 'session',
            'provider' =&amp;gt; 'users',
        ],

        'api' =&amp;gt; [
            'driver' =&amp;gt; 'jwt',
            'provider' =&amp;gt; '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' =&amp;gt; [
        'users' =&amp;gt; [
            'driver' =&amp;gt; 'eloquent',
            'model' =&amp;gt; App\Models\User::class,
        ],

        // 'users' =&amp;gt; [
        //     'driver' =&amp;gt; 'database',
        //     'table' =&amp;gt; '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' =&amp;gt; [
        'users' =&amp;gt; [
            'provider' =&amp;gt; 'users',
            'table' =&amp;gt; 'password_reset_tokens',
            'expire' =&amp;gt; 60,
            'throttle' =&amp;gt; 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' =&amp;gt; 10800,

];


&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;&lt;strong&gt;STEP 5: UPDATE USER MODEL&lt;/strong&gt;&lt;br&gt;
Now all are set to go. Now we have to update the User model like below. So update it to create laravel jwt auth:&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;app\Models\User.php&lt;/strong&gt;&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;

&amp;lt;?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&amp;lt;int, string&amp;gt;
     */
    protected $fillable = [
        'name',
        'email',
        'password',
    ];

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

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

    /**
     * Get the identifier that will be stored in the subject claim of the JWT.
     *
     * @return mixed
     */
    public function getJWTIdentifier()
    {
        return $this-&amp;gt;getKey();
    }

    /**
     * Return a key value array, containing any custom claims to be added to the JWT.
     *
     * @return array
     */
    public function getJWTCustomClaims()
    {
        return [];
    }
}



&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;&lt;strong&gt;STEP 6: CREATE CONTROLLER&lt;/strong&gt;&lt;br&gt;
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:&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;

php artisan make:controller API/AuthController


&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;Now update this controller like this:&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;

&amp;lt;?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-&amp;gt;middleware('auth:api', ['except' =&amp;gt; ['login', 'register']]);
    }

    public function login(Request $request)
    {
        $request-&amp;gt;validate([
            'email' =&amp;gt; 'required|string|email',
            'password' =&amp;gt; 'required|string',
        ]);
        $credentials = $request-&amp;gt;only('email', 'password');
        $token = Auth::attempt($credentials);

        if (!$token) {
            return response()-&amp;gt;json([
                'message' =&amp;gt; 'Unauthorized',
            ], 401);
        }

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

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

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

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

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

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


&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;&lt;strong&gt;STEP 7: CREATE ROUTE&lt;/strong&gt;&lt;br&gt;
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:&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;routes/api.php&lt;/strong&gt;&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;

&amp;lt;?php

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

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


&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;Now if you start your server by running &lt;strong&gt;php artisan serve&lt;/strong&gt; and test all API via Postman like this:&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;

http://127.0.0.1:8000/api/register


&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;
&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;

http://127.0.0.1:8000/api/login


&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;
&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;

http://127.0.0.1:8000/api/refresh


&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;
&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;

http://127.0.0.1:8000/api/logout


&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

</description>
      <category>jwt</category>
      <category>api</category>
      <category>laravel</category>
      <category>authentication</category>
    </item>
  </channel>
</rss>
