Laravel / Laravel API Development
Implementing JWT and Sanctum Authentication
This tutorial will show you how to secure your Laravel API using JWT and Sanctum authentication. You'll learn how to handle authentication and protect your routes and resources.
Section overview
5 resourcesCovers building RESTful APIs using Laravel for modern web applications.
1. Introduction
Brief explanation of the tutorial's goal
This tutorial aims to guide you through the process of implementing JWT (JSON Web Tokens) and Sanctum Authentication in a Laravel API. This will help you secure your application by ensuring only authenticated users can access specific routes.
What the user will learn
By the end of this tutorial, you will be able to:
- Understand JWT and Sanctum authentication
- Implement JWT authentication
- Implement Sanctum authentication
- Secure routes using these authentication methods
Prerequisites
Before proceeding, you should have:
- Basic knowledge of Laravel and its structure
- PHP environment set up with Laravel installed
- A text editor, such as Visual Studio Code
- Basic knowledge of API development
2. Step-by-Step Guide
JWT Authentication
JWT authentication involves generating a token when the user logs in and then sending this token with each request to authenticate the user.
-
Install JWT Package: To use JWT in Laravel, we need to install the
tymon/jwt-authpackage. Runcomposer require tymon/jwt-authin your terminal. -
Generate JWT Secret: Next, generate a JWT secret using
php artisan jwt:secret. This will update your.envfile with a new line:JWT_SECRET=secret. -
Implement JWT: In your
AuthController, use the JWT package to implement authentication. Below is a simplified version:
public function login(Request $request) {
$credentials = $request->only('email', 'password');
if (! $token = auth()->attempt($credentials)) {
return response()->json(['error' => 'Invalid credentials'], 401);
}
return response()->json(['token' => $token]);
}
Here, we attempt to validate the user's credentials. If valid, a JWT token is generated and returned.
Sanctum Authentication
Sanctum provides a featherweight authentication system for SPAs (single page applications), mobile applications, and simple, token-based APIs.
-
Install Sanctum Package: Install the
laravel/sanctumpackage using composer by runningcomposer require laravel/sanctum. -
Publish Sanctum Configuration: Next, publish the Sanctum configuration and migration files using
php artisan vendor:publish --provider="Laravel\Sanctum\SanctumServiceProvider". -
Run Migrations: Run
php artisan migrateto create the necessary database tables. -
Configure API Middleware: In your
apimiddleware group, ensure you have theEnsureFrontendRequestsAreStateful::classandAuthenticate::class. -
Use Sanctum's Capabilities: Sanctum offers many methods for authentication, such as
check,user,guardand more. Here's a simplified usage example:
public function user(Request $request)
{
return $request->user();
}
This method will return the authenticated user's instance.
3. Code Examples
JWT Authentication
The following is a more in-depth example of a login method using JWT:
public function login(Request $request) {
$credentials = $request->only('email', 'password');
if (!$token = JWTAuth::attempt($credentials)) {
return response()->json(['error' => 'Invalid credentials'], 401);
}
return response()->json(['token' => $token]);
}
This method receives a request, attempts to authenticate the user, and if successful, returns a JWT.
Sanctum Authentication
Consider this example of a route that requires authentication:
Route::middleware('auth:sanctum')->get('/user', function (Request $request) {
return $request->user();
});
This route will return the authenticated user's instance, or a 401 status code if the user is not authenticated.
4. Summary
In this tutorial, we've covered JWT and Sanctum authentication in Laravel. We've learned how to install necessary packages, generate tokens, and protect routes. We've also provided examples of how to authenticate users and return authenticated user's instances.
5. Practice Exercises
-
Exercise 1: Create a registration route that returns a JWT token upon successful registration.
-
Exercise 2: Create a route that requires Sanctum authentication and returns a list of all registered users.
-
Exercise 3: Create a logout route that invalidates the user's JWT token.
Remember, the key to mastering these concepts is practice. Try implementing these methods in your projects, and experiment with different methods offered by both packages to familiarize yourself with their capabilities.
Need Help Implementing This?
We build custom systems, plugins, and scalable infrastructure.
Related topics
Keep learning with adjacent tracks.
Popular tools
Helpful utilities for quick tasks.
Latest articles
Fresh insights from the CodiWiki team.
AI in Drug Discovery: Accelerating Medical Breakthroughs
In the rapidly evolving landscape of healthcare and pharmaceuticals, Artificial Intelligence (AI) in drug dis…
Read articleAI in Retail: Personalized Shopping and Inventory Management
In the rapidly evolving retail landscape, the integration of Artificial Intelligence (AI) is revolutionizing …
Read articleAI in Public Safety: Predictive Policing and Crime Prevention
In the realm of public safety, the integration of Artificial Intelligence (AI) stands as a beacon of innovati…
Read articleAI in Mental Health: Assisting with Therapy and Diagnostics
In the realm of mental health, the integration of Artificial Intelligence (AI) stands as a beacon of hope and…
Read articleAI in Legal Compliance: Ensuring Regulatory Adherence
In an era where technology continually reshapes the boundaries of industries, Artificial Intelligence (AI) in…
Read article