Authentication & Authorization in Laravel 11: Passport, Sanctum, Custom Guards, and JWT

Jayprakash Jangir
4 min readJun 25, 2024

In Laravel 11, authentication and authorization can be achieved using various methods such as Passport, Sanctum, custom guards, and JWT. Each method has its specific use cases and benefits. This blog post will provide a detailed overview of these methods along with code snippets and scenarios where each method would be most effective.

Table of Contents

1) Introduction to Authentication & Authorization

2) Laravel Passport

  • Introduction
  • Installation and Setup
  • Usage

3) Laravel Sanctum

  • Introduction
  • Installation and Setup
  • Usage

4) Custom Guards

  • Introduction
  • Setting Up Custom Guards
  • Usage

5) JWT (JSON Web Tokens)

  • Introduction
  • Installation and Setup
  • Usage

6) Scenarios for Use

7) Conclusion

1. Introduction to Authentication & Authorization

Authentication verifies the identity of a user, while authorization determines the permissions and access levels of that user. Laravel 11 provides multiple tools to handle authentication and authorization efficiently, catering to various project requirements.

2. Laravel Passport

Introduction

Laravel Passport is an OAuth2 server implementation for API authentication. It provides a full OAuth2 server implementation and makes it easy to generate access tokens for API clients.

Installation and Setup

1. Install Passport via Composer:

composer require laravel/passport

2. Run the migrations:

php artisan migrate

3. Install Passport:

php artisan passport:install

4. Add the Passport service provider in config/app.php:

'providers' => [     

// Other service providers...

Laravel\Passport\PassportServiceProvider::class,

],

5. Configure the Auth guard in config/auth.php:

'api' => [     
'driver' => 'passport',
'provider' => 'users',
],

6. Add the HasApiTokens trait to your User model:

use Laravel\Passport\HasApiTokens;  

class User extends Authenticatable {

use HasApiTokens, Notifiable;

}

7. Register the routes in AuthServiceProvider:

use Laravel\Passport\Passport;  

public function boot() {

$this->registerPolicies();

Passport::routes();

}

Usage

To issue a token, you can make a POST request to the /oauth/token endpoint with the client's credentials:

curl -X POST http://your-app.test/oauth/token \
-H "Content-Type: application/json" \
-d '{
"grant_type": "password",
"client_id": "client-id",
"client_secret": "client-secret",
"username": "user@example.com",
"password": "user-password",
"scope": ""
}'

3. Laravel Sanctum

Introduction

Laravel Sanctum provides a simple authentication system for SPAs (Single Page Applications), mobile applications, and simple token-based APIs. It allows each user of your application to generate multiple API tokens for their account.

Installation and Setup

1. Install Sanctum via Composer:

composer require laravel/sanctum

2. Publish the Sanctum configuration:

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

3. Run the migrations:

php artisan migrate

4. Add Sanctum’s middleware in api middleware group within your app/Http/Kernel.php file:

'api' => [
\Laravel\Sanctum\Http\Middleware\EnsureFrontendRequestsAreStateful::class,
'throttle:api',
\Illuminate\Routing\Middleware\SubstituteBindings::class,
],

5. Add the HasApiTokens trait to your User model:

use Laravel\Sanctum\HasApiTokens;  

class User extends Authenticatable {

use HasApiTokens, Notifiable;

}

Usage

To issue a token, you can call the createToken method on the User model:

use App\Models\User;

Route::post('/login', function (Request $request) {
$user = User::where('email', $request->email)->first();

if (! $user || ! Hash::check($request->password, $user->password)) {
return response()->json(['message' => 'Unauthorized'], 401);
}

return $user->createToken('token-name')->plainTextToken;
});

4. Custom Guards

Introduction

Custom guards in Laravel allow you to define how users are authenticated for each request. You can create your custom guard by implementing the Illuminate\Contracts\Auth\Guard contract.

Setting Up Custom Guards

1. Define a custom guard in config/auth.php:

'guards' => [     
'custom' => [
'driver' => 'custom-driver',
'provider' => 'users',
],
],

2. Create the custom guard class:

namespace App\Auth;

use Illuminate\Contracts\Auth\Guard;
use Illuminate\Contracts\Auth\UserProvider;
use Illuminate\Contracts\Auth\Authenticatable;

class CustomGuard implements Guard
{
protected $user;

public function __construct(UserProvider $provider)
{
$this->provider = $provider;
}

public function user()
{
return $this->user;
}

public function check()
{
return ! is_null($this->user());
}

public function setUser(Authenticatable $user)
{
$this->user = $user;
}

// Other methods required by the Guard contract...
}

3. Register the custom guard in AuthServiceProvider:

use App\Auth\CustomGuard;

public function boot()
{
$this->app['auth']->extend('custom-driver', function ($app, $name, array $config) {
return new CustomGuard($app['auth']->createUserProvider($config['provider']));
});
}

5. JWT (JSON Web Tokens)

Introduction

JWT (JSON Web Tokens) are an open standard for securely transmitting information between parties as a JSON object. JWTs are commonly used for authentication in web applications.

Installation and Setup

1. Install the tymon/jwt-auth package via Composer:

composer require tymon/jwt-auth

2. Publish the configuration:

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

3. Generate the secret key:

php artisan jwt:secret

4. Update config/auth.php to use JWT as the driver for the API guard:

'guards' => [
'api' => [
'driver' => 'jwt',
'provider' => 'users',
],
],

Usage

To issue a token, you can create a login method in your controller:

use Tymon\JWTAuth\Facades\JWTAuth;

public function login(Request $request)
{
$credentials = $request->only('email', 'password');
if (! $token = JWTAuth::attempt($credentials)) {
return response()->json(['error' => 'Unauthorized'], 401);
}
return response()->json(['token' => $token]);
}

6. Scenarios for Use

  • Laravel Passport: Best suited for applications that require a full OAuth2 server implementation, such as when building an API that needs to authenticate third-party clients.
  • Laravel Sanctum: Ideal for SPAs, mobile applications, and simple token-based APIs where a lightweight authentication system is sufficient.
  • Custom Guards: Useful when you need to implement custom authentication logic that doesn’t fit into the default Laravel authentication drivers.
  • JWT: Perfect for stateless API authentication, especially when you need to manage user sessions on a client-side application without storing session data on the server.

7. Conclusion

Laravel 11 offers a variety of methods for implementing authentication and authorization in your application. Whether you need the full OAuth2 capabilities of Passport, the simplicity of Sanctum, the flexibility of custom guards, or the stateless nature of JWT, Laravel provides the tools you need to secure your application effectively. By understanding the strengths and scenarios for each method, you can choose the right approach for your specific requirements.

--

--