Laravel JWT Tutorial: A comprehensive guide
Introduction to laravel jwt authentication:
JSON Web Token (JWT) authentication is a popular method used for secure user authentication in web applications. In this tutorial, we will learn how to implement JWT authentication in a Laravel project. By the end of this guide, you will have a fully functional Laravel application with JWT-based authentication, enabling you to create secure and stateless APIs.
Key Features:
- User Registration: We will build an API endpoint to allow users to register and store their information in the database.
- User Login: Users will be able to log in using their registered credentials and receive a JWT token for authentication.
- JWT Token Refresh: Users can refresh their JWT tokens to extend their session and maintain continuous access.
- Access User Information: An API endpoint will provide authenticated users with their profile information using their JWT token.
Prerequisites:
Before getting started, ensure you have the following prerequisites:
- PHP installed on your local machine.
- Composer – Dependency manager for PHP, available at https://getcomposer.org/download/.
- Laravel installed – You can install it via Composer using the command:
composer global require laravel/installer
. - A database (e.g., MySQL, PostgreSQL) and the necessary credentials.
Step-by-Step Process:
Step 1: Create a new Laravel project
Open your terminal and execute the following command to create a new Laravel project:
laravel new LaravelJwtAuthentication
Step 2: Create a users table
Define the database table structure for storing user information. Open the migration file using the command:
php artisan make:migration create_users_table
Update the migration file with the necessary fields for the users table and execute the migration:
php artisan migrate
Step 3: Install JWT dependency
To use JWT in Laravel, we need to install the tymon/jwt-auth
package. Run the following command:
composer require tymon/jwt-auth
Next, publish the JWT configuration file:
Set Up JWT Package We’ll use the tymon/jwt-auth
package for handling JWT authentication. Open your terminal and navigate to the root directory of your Laravel project. Run the following commands:
composer require tymon/jwt-auth
php artisan vendor:publish --provider="Tymon\JWTAuth\Providers\LaravelServiceProvider"
php artisan jwt:secret
Configure JWT Open the config/auth.php
file and modify the guards
and providers
arrays as follows:
// config/auth.php
'guards' => [
'api' => [
'driver' => 'jwt',
'provider' => 'users',
],
],
'providers' => [
'users' => [
'driver' => 'eloquent',
'model' => App\Models\User::class,
],
],
Step 4: Create a Controller
Create a new controller to handle user registration and login:
php artisan make:controller AuthController
Step 5: Create a User Model
Generate a new Eloquent model for the users table:
php artisan make:model User
<?php
namespace App\Models;
use Illuminate\Contracts\Auth\MustVerifyEmail;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable;
use Tymon\JWTAuth\Contracts\JWTSubject;
class User extends Authenticatable implements JWTSubject
{
use 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: Define Routes
Define the API routes for user registration, login, and other functionalities in the routes/api.php
file.
<?php
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Route;
use App\Http\Controllers\AuthController;
/*
|--------------------------------------------------------------------------
| API Routes
|--------------------------------------------------------------------------
|
| Here is where you can register API routes for your application. These
| routes are loaded by the RouteServiceProvider and all of them will
| be assigned to the "api" middleware group. Make something great!
|
*/
Route::middleware('auth:sanctum')->get('/user', function (Request $request) {
return $request->user();
});
Route::post('login', [AuthController::class,'login']);
Route::post('logout', [AuthController::class,'logout']);
Route::post('register', [AuthController::class,'register']);
Route::middleware('auth:api')->group(function () {
// Your authenticated routes go here
Route::post('refresh', [AuthController::class,'refresh']);
Route::post('me', [AuthController::class,'me']);
});
Step 7: Implement Controller Logic
Inside the AuthController
, implement the logic for user registration, login, token refresh, and fetching user data.
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use App\Http\Controllers\Controller;
use App\Models\User;
use Tymon\JWTAuth\Facades\JWTAuth;
class AuthController extends Controller
{
public function register(Request $request)
{
$this->validate($request, [
'name' => 'required|string|max:255',
'email' => 'required|string|email|max:255|unique:users',
'password' => 'required|string|min:6',
]);
$user = new User([
'name' => $request->input('name'),
'email' => $request->input('email'),
'password' => bcrypt($request->input('password')),
]);
$user->save();
return response()->json(['message' => 'Successfully registered'], 201);
}
public function login(Request $request)
{
$credentials = $request->only('email', 'password');
if ($token = JWTAuth::attempt($credentials)) {
return response()->json(['token' => $token]);
}
return response()->json(['error' => 'Unauthorized'], 401);
}
public function logout()
{
Auth::logout();
return response()->json(['message' => 'Successfully logged out']);
}
protected function respondWithToken($token)
{
$payload = JWTAuth::getPayload($token);
$expiration = $payload->get('exp');
return response()->json([
'access_token' => $token,
'token_type' => 'bearer',
'expires_in' => $expiration - time() // Calculate the remaining time in seconds
]);
}
public function me(Request $request)
{
$user = JWTAuth::user();
if (!$user) {
return response()->json(['error' => 'Unauthorized'], 401);
}
return response()->json(['user' => $user]);
}
}
Testing the JWT Authentication: To test the JWT authentication, you can use tools like Postman or cURL.
User Registration:
- Use Postman to send a POST request to
/api/register
with the user’sname
,email
, andpassword
as JSON data. - You should receive a successful response indicating the user registration.
- Select the “Body” tab below the URL and choose “raw” with the content type set to “JSON.”
- In the request body, enter the user registration data in JSON format. For example:
{
"name": "John Doe",
"email": "john.doe@example.com",
"password": "secret123"
}
User Login:
- Send a POST request to
/api/login
with the user’semail
andpassword
as JSON data. - The response will include a JWT token, which you can use for further authentication.
{
"email": "john.doe@example.com",
"password": "secret123"
}
Fetch User Data:
- Use the obtained JWT token as a bearer token in the Authorization header and send a GET request to
/api/me
. - The response should contain the authenticated user’s data.
Token Refresh:
- To refresh the token, send a POST request to
/api/refresh
with the JWT token in the Authorization header. - The response will provide a new JWT token with an extended expiration time.
Conclusion:
In this tutorial, we have successfully implemented JWT authentication in a Laravel project. We created a user registration and login system, integrated JWT to generate secure tokens, and used them to fetch user data. With JWT, our Laravel application now has a robust and stateless authentication system, making it an excellent foundation for building secure and scalable APIs. Happy coding!
Our Recommendation
- Top 30 Laravel Interview Questions: A comprehensive guide
- Middleware in Laravel: A Comprehensive Guide
- Laravel vs CodeIgniter: Framework Comparison
- How to Generate PDF Files Using Dompdf in Laravel
- Laravel Pagination Example customizations
- Laravel Relationship: Unlock power of Data with
- CRUD Operations in Laravel 9 – A comprehensive guide
- Laravel login Authentication in Laravel 9
- User Registration in Laravel Example: Simple Steps to Get Started
- Import and Export Excel in Laravel: A Step-by-Step Guide
- Laravel JWT Tutorial: A comprehensive guide
- Laravel Passport: A comprehensive guide in Laravel 10
Akhand Pratap Singh
Related Post
Newsletter
Recent Posts
- How to Upload Image into Database Using PHP
- Inheritance in PHP: A comprehensive guide
- Image Resize in Laravel 10 : A comprehensive Guide
- Laravel Passport: A comprehensive guide in Laravel 10
- Laravel JWT Tutorial: A comprehensive guide
- Import and Export Excel in Laravel: A Step-by-Step Guide
- Rest API in PHP: Building Powerful and Scalable Web Services
- Array to String in PHP – A Comprehensive Guide
- Event Loop in JavaScript: A comprehensive guide
- Ternary Operator in JavaScript: A Comprehensive Guide