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.
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
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
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-auth
package. Run composer require tymon/jwt-auth
in your terminal.
Generate JWT Secret: Next, generate a JWT secret using php artisan jwt:secret
. This will update your .env
file 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 provides a featherweight authentication system for SPAs (single page applications), mobile applications, and simple, token-based APIs.
Install Sanctum Package: Install the laravel/sanctum
package using composer by running composer 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 migrate
to create the necessary database tables.
Configure API Middleware: In your api
middleware group, ensure you have the EnsureFrontendRequestsAreStateful::class
and Authenticate::class
.
Use Sanctum's Capabilities: Sanctum offers many methods for authentication, such as check
, user
, guard
and more. Here's a simplified usage example:
public function user(Request $request)
{
return $request->user();
}
This method will return the authenticated user's instance.
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.
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.
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.
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.