Introduction:
Welcome to our tutorial! In this guide, we’ll walk you through the process of implementing JWT authentication in Laravel 11. JWT (JSON Web Token) provides a robust method for securing your API endpoints, making it easy to authenticate users via tokens, manage access, and integrate with third-party services.
Install and Setup jwt-auth:
In Laravel 11, the api.php
routes file is not created by default. You can create this file by running the following command:
If you are working on an existing Laravel 11 project and have already created api.php
, you can install the jwt-auth package using the following command:
composer require tymon/jwt-auth
Publish the config:
php artisan vendor:publish --provider="Tymon\JWTAuth\Providers\LaravelServiceProvider"
This will create a config/jwt.php
file that allows you to configure this package.
generate secret key:
This command will add a line similar to JWT_SECRET=foobar to your .env file. This key is crucial for signing your tokens, and the specific process will vary based on the algorithm you select.
Update your User model:
Implement JWTSubject
Contract. Add getJWTIdentifier, getJWTCustomClaims
methods in User.php
use Tymon\JWTAuth\Contracts\JWTSubject;
use Illuminate\Notifications\Notifiable;
use Illuminate\Foundation\Auth\User as Authenticatable;
class User extends Authenticatable implements JWTSubject
{
use Notifiable;
// Rest omitted for brevity
/**
* 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 [];
}
}
Configure Guard:
Add this to you config/auth.php
guards array:
'api' => [
'driver' => 'jwt',
'provider' => 'users'
]
Database configuration:
Ensure your database configuration in the .env
file is correctly set up:
DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=your_database_name
DB_USERNAME=your_username
DB_PASSWORD=your_password
Run the database migrations to create the necessary tables:
Authenticating user & create token
Add the following code to your api.php
routes file. This will validate the user credentials and generate an API access token:
use App\Http\Controllers\AuthController;
Route::post('/register', [AuthController::class, 'register']);
Route::post('/login', [AuthController::class, 'login']);
Route::post('/logout', [AuthController::class, 'logout'])->middleware('auth:api');
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use App\Models\User;
use Illuminate\Support\Facades\Hash;
use Illuminate\Validation\ValidationException;
class AuthController extends Controller
{
/**
* Handle a registration request for the application.
*/
public function register(Request $request)
{
$request->validate([
'name' => 'required|string|max:255',
'email' => 'required|string|email|max:255|unique:users',
'password' => 'required|string|min:8|confirmed',
]);
$user = User::create([
'name' => $request->name,
'email' => $request->email,
'password' => Hash::make($request->password),
]);
return response()->json([
'message' => 'User registered successfully',
'user' => $user
], 201);
}
/**
* Handle a login request for the application.
*/
public function login(Request $request)
{
$request->validate([
'email' => 'required|email',
'password' => 'required'
]);
if (!$token = Auth::attempt($request->only('email', 'password'))) {
throw ValidationException::withMessages([
'email' => ['The provided credentials are incorrect.'],
]);
}
return response()->json([
'message' => 'User logged in successfully',
'access_token' => $token,
'token_type' => 'Bearer',
]);
}
/**
* Handle a logout request for the application.
*/
public function logout(Request $request)
{
Auth::logout();
return response()->json([
'message' => 'User logged out successfully'
]);
}
}
Protecting routes:
To access protected routes, users will need to pass the token in the request headers. Here’s how you can protect a route using auth:api
middleware:
Route::get('/user', function (Request $request) {
return $request->user();
})->middleware('auth:api');
Conclusion:
That's it! You have successfully set up the jwt-auth api authentication in your Laravel 11 app.