Home > Web Development > Laravel Tutorials > Complete guide on authentication in Laravel 11 with JWT and Sanctum.

Complete guide on authentication in Laravel 11 with JWT and Sanctum.

Diego Cortés
Diego Cortés
January 20, 2025
Complete guide on authentication in Laravel 11 with JWT and Sanctum.

Authentication in web applications is a crucial aspect to ensure the security and data protection of users. Laravel 11 offers several options for implementing authentication, with JWT (JSON Web Tokens) and Sanctum being two of the most popular. In this article, we will explore how to implement these methods in Laravel 11, providing a clear and understandable guide.

What is JWT?

JWT, or JSON Web Tokens, is an open standard that allows the secure transmission of information between parties as a JSON object. This token is commonly used to authenticate requests and authorize access to specific resources. By using JWT, the user's information is encoded in a format readable by the server, allowing verification of identity without the need for server-side sessions.

What is Sanctum?

Sanctum is a Laravel package designed for the authentication of SPA (Single Page Applications) and APIs. Unlike Passport, which uses OAuth2, Sanctum offers a simple way of authentication using API tokens, ideal for lighter applications and web services.

Setting Up JWT in Laravel 11

To implement JWT in Laravel 11, the first step is to install the tymon/jwt-auth package. This can be done using Composer with the following command:

composer require tymon/jwt-auth

Once installed, you must publish the package configuration by running:

php artisan vendor:publish --provider="Tymon\JWTAuth\JWTAuthServiceProvider"

This will generate a configuration file config/jwt.php. Next, it is recommended to generate a secret key for the JWT:

php artisan jwt:secret

With this, the installation and configuration steps are complete. Now, you should create the logic for user authentication, which generally includes creating a controller to handle registration and login. A simple example of a login method could be:

public function login(Request $request)
{
    $credentials = $request->only('email', 'password');

    if (!$token = auth()->attempt($credentials)) {
        return response()->json(['error' => 'Unauthorized'], 401);
    }

    return response()->json(['token' => $token]);
}

Setting Up Sanctum in Laravel 11

To use Sanctum, you first need to install it as well using Composer:

composer require laravel/sanctum

After installation, publish the configuration by running:

php artisan vendor:publish --provider="Laravel\Sanctum\SanctumServiceProvider"

Next, make sure to add the Sanctum middleware in your api.php file:

Laravel\Sanctum\Http\Middleware\EnsureFrontendRequestsAreStateful::class,

This will allow Sanctum to handle the authentication of requests from the client. Finally, to authenticate a user, you can create a controller similar to the one for JWT, using createToken to generate an access token:

public function login(Request $request)
{
    $credentials = $request->only('email', 'password');

    if (Auth::attempt($credentials)) {
        $user = Auth::user();
        $token = $user->createToken('API Token')->plainTextToken;
        return response()->json(['token' => $token]);
    }

    return response()->json(['error' => 'Unauthorized'], 401);
}

Conclusions

Both JWT and Sanctum are powerful options that Laravel 11 offers for user authentication in web applications. Each has its characteristics and is ideal for different types of applications. The choice between JWT and Sanctum will depend on the specific requirements of your project.

If you want to delve deeper into this topic and keep up with the latest news on Laravel and web development, I invite you to read more articles of this kind on my blog.

Diego Cortés
Diego Cortés
Full Stack Developer, SEO Specialist with Expertise in Laravel & Vue.js and 3D Generalist

Categories

Page loaded in 22.69 ms