. Hello, world!

In Laravel, JWT (JSON Web Token) authentication can be implemented using libraries such as tymon/jwt-auth or lcobucci/jwt. When dealing with multiple guards, you typically need to specify which guard should handle the JWT authentication process, and ensure that the correct guard is used for each type of user or request.

Here’s how you can set up JWT authentication with multiple guards in a Laravel application:
Step 1: Install the JWT Auth package

To start, you need to install the tymon/jwt-auth package (or any other JWT package) using Composer.

composer require tymon/jwt-auth

After installation, publish the configuration file:

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

This will create a config/jwt.php file that you can configure based on your needs.
Step 2: Configure Guards in config/auth.php

In the config/auth.php file, configure multiple guards. A common setup would be to have a web guard for users interacting with the website, and an api guard for API requests.

You can configure different guards with JWT authentication as follows:

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

   'api' => [
       'driver' => 'jwt',  // This tells Laravel to use JWT for this guard
       'provider' => 'users',
   ],

   // Example of another guard for admin
   'admin' => [
       'driver' => 'jwt',
       'provider' => 'admins',
   ],
],

In this setup:

   api guard uses JWT for regular API users.
   admin guard uses JWT for admin users.

Step 3: Set up User and Admin Models

Make sure your User and Admin models implement the Tymon\JWTAuth\Contracts\JWTSubject interface. This allows these models to be JWT-authenticated.

In User.php (typically in app/Models/User.php):

use Tymon\JWTAuth\Contracts\JWTSubject;

class User extends Authenticatable implements JWTSubject
{
   // Other model code...

   public function getJWTIdentifier()
   {
       return $this->getKey();  // Return the primary key of the user
   }

   public function getJWTCustomClaims()
   {
       return [];  // You can add custom claims here
   }
}

In Admin.php (typically in app/Models/Admin.php):

use Tymon\JWTAuth\Contracts\JWTSubject;

class Admin extends Authenticatable implements JWTSubject
{
   // Other model code...

   public function getJWTIdentifier()
   {
       return $this->getKey();  // Return the primary key of the admin
   }

   public function getJWTCustomClaims()
   {
       return [];  // You can add custom claims here
   }
}

Step 4: Set Up Authentication Controllers

You’ll need a controller to handle user login and authentication. Create a controller using the following:

php artisan make:controller AuthController

In the controller, handle authentication for both the api and admin guards.

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Tymon\JWTAuth\Facades\JWTAuth;
use App\Models\User;
use App\Models\Admin;

class AuthController extends Controller
{
   // Login for regular user
   public function login(Request $request)
   {
       $credentials = $request->only('email', 'password');

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

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

   // Login for admin user
   public function adminLogin(Request $request)
   {
       $credentials = $request->only('email', 'password');

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

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

   // Get current user (for regular users)
   public function userProfile(Request $request)
   {
       $user = JWTAuth::guard('api')->user();  // Use 'api' guard to get user
       return response()->json(compact('user'));
   }

   // Get current admin (for admin users)
   public function adminProfile(Request $request)
   {
       $admin = JWTAuth::guard('admin')->user();  // Use 'admin' guard to get admin
       return response()->json(compact('admin'));
   }
}

Step 5: Define Routes

In routes/api.php, define routes for login and getting user profiles.

use App\Http\Controllers\AuthController;

Route::post('login', [AuthController::class, 'login']);
Route::post('admin/login', [AuthController::class, 'adminLogin']);
Route::get('user/profile', [AuthController::class, 'userProfile'])->middleware('auth:api');
Route::get('admin/profile', [AuthController::class, 'adminProfile'])->middleware('auth:admin');

Step 6: Protect Routes Using Guards

You’ve already set up the guards in your routes, but you also need to ensure that they are used correctly for protection.

In routes/api.php:

   The auth:api middleware is used for regular users.
   The auth:admin middleware is used for admin users.

Route::middleware('auth:api')->get('user/profile', function (Request $request) {
   return $request->user();
});

Route::middleware('auth:admin')->get('admin/profile', function (Request $request) {
   return $request->user();
});

Step 7: Testing

   Login: Send a POST request to /login for a user or /admin/login for an admin, passing the email and password. If credentials are correct, you'll receive a JWT token.

   Access Protected Routes: Send a GET request to /user/profile or /admin/profile with the Authorization header set as Bearer {token}.

Authorization: Bearer {jwt_token}

Conclusion

This setup allows you to use JWT authentication with multiple guards in Laravel for both regular users and admins. You can extend this approach by adding more guards if necessary, or customize the behavior for different types of users.

Let me know if you need any more details!