Implementing JWT and Sanctum Authentication

Tutorial 2 of 5

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.

  1. 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.

  2. 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.

  3. 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.

  1. Install Sanctum Package: Install the laravel/sanctum package using composer by running composer require laravel/sanctum.

  2. Publish Sanctum Configuration: Next, publish the Sanctum configuration and migration files using php artisan vendor:publish --provider="Laravel\Sanctum\SanctumServiceProvider".

  3. Run Migrations: Run php artisan migrate to create the necessary database tables.

  4. Configure API Middleware: In your api middleware group, ensure you have the EnsureFrontendRequestsAreStateful::class and Authenticate::class.

  5. 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.

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

  1. Exercise 1: Create a registration route that returns a JWT token upon successful registration.

  2. Exercise 2: Create a route that requires Sanctum authentication and returns a list of all registered users.

  3. 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.