Convert Figma logo to code with AI

laravel logosanctum

Laravel Sanctum provides a featherweight authentication system for SPAs and simple APIs.

2,730
293
2,730
1

Top Related Projects

Associate users with roles and permissions

11,274

🔐 JSON Web Token Authentication for Laravel & Lumen

Laravel Passport provides OAuth2 server support to Laravel.

1,599

Backend controllers and scaffolding for Laravel authentication.

9,353

PHP package for JWT

9,325

A RESTful API package for the Laravel and Lumen frameworks.

Quick Overview

Laravel Sanctum is a lightweight authentication system for single-page applications (SPAs), mobile applications, and simple, token-based APIs. It provides a simple, expressive API to issue, revoke, and manage personal access tokens.

Pros

  • Lightweight and Focused: Sanctum is a lightweight package that focuses solely on authentication, making it a great choice for simple API-based applications.
  • Easy to Implement: Sanctum's straightforward implementation and configuration make it a quick and easy solution for adding authentication to your Laravel application.
  • Flexible Token Management: Sanctum allows you to manage personal access tokens, making it easy to revoke or refresh tokens as needed.
  • Seamless Integration with Laravel: As a first-party package, Sanctum integrates seamlessly with the Laravel ecosystem, leveraging the framework's existing features and conventions.

Cons

  • Limited Functionality: Sanctum is a focused package, which means it may not provide all the features and functionality of more comprehensive authentication solutions.
  • Lack of Social Login: Sanctum does not provide built-in support for social login integrations, which may be a requirement for some applications.
  • Potential Performance Impact: The use of personal access tokens may have a slight performance impact compared to more lightweight authentication methods, such as session-based authentication.
  • Limited Customization: While Sanctum is flexible, it may not offer the same level of customization as other authentication packages, which could be a drawback for complex or highly specialized use cases.

Code Examples

Issuing a Personal Access Token

use Laravel\Sanctum\Sanctum;

// Create a new personal access token
$token = $user->createToken('token-name')->plainTextToken;

This code demonstrates how to create a new personal access token for a user.

Authenticating with a Personal Access Token

use Illuminate\Http\Request;

// Authenticate the request using the personal access token
$request->user()->tokens()->where('name', 'token-name')->first()->delete();

This code shows how to authenticate a request using a personal access token and how to revoke the token.

Protecting a Route with Sanctum

use Laravel\Sanctum\Http\Middleware\EnsureFrontendRequestsAreStateful;

// Protect a route with Sanctum's middleware
Route::middleware([EnsureFrontendRequestsAreStateful::class, 'auth:sanctum'])->group(function () {
    Route::get('/user', function (Request $request) {
        return $request->user();
    });
});

This code demonstrates how to protect a route using Sanctum's middleware, ensuring that only authenticated users can access the route.

Getting Started

To get started with Laravel Sanctum, follow these steps:

  1. Install the Sanctum package using Composer:
composer require laravel/sanctum
  1. Publish the Sanctum configuration file and migration:
php artisan vendor:publish --provider="Laravel\Sanctum\SanctumServiceProvider"
  1. Run the migration to create the necessary database tables:
php artisan migrate
  1. In your app/Http/Kernel.php file, add the EnsureFrontendRequestsAreStateful middleware to the api middleware group:
protected $middlewareGroups = [
    'web' => [
        // ...
    ],

    'api' => [
        'throttle:api',
        \Illuminate\Routing\Middleware\SubstituteBindings::class,
        \Laravel\Sanctum\Http\Middleware\EnsureFrontendRequestsAreStateful::class,
    ],
];
  1. In your application, you can now use Sanctum's API to issue, revoke, and manage personal access tokens.

Competitor Comparisons

Associate users with roles and permissions

Pros of Laravel Permission

  • More granular control over roles and permissions
  • Supports hierarchical roles and permissions
  • Provides database caching for improved performance

Cons of Laravel Permission

  • Requires more setup and configuration
  • Can be overkill for simple authentication needs
  • May have a steeper learning curve for beginners

Code Comparison

Laravel Permission:

$user->givePermissionTo('edit articles');
$user->assignRole('writer');
if ($user->hasPermissionTo('edit articles')) {
    // User can edit articles
}

Sanctum:

$user->createToken('api-token')->plainTextToken;
if ($user->tokenCan('edit-articles')) {
    // User can edit articles
}

Laravel Permission offers more detailed control over user roles and permissions, allowing for complex hierarchies and granular access control. It's well-suited for applications with intricate permission structures but may be excessive for simpler projects.

Sanctum, on the other hand, provides a lightweight authentication system for SPAs, mobile apps, and simple token-based APIs. It's easier to set up and use but offers less granular control over permissions.

The choice between the two depends on the specific needs of your project, with Laravel Permission being more suitable for complex permission systems and Sanctum for simpler authentication requirements.

11,274

🔐 JSON Web Token Authentication for Laravel & Lumen

Pros of jwt-auth

  • Provides more flexibility in token management and customization
  • Supports multiple authentication guards and providers
  • Can be used across different platforms and languages due to JWT standard

Cons of jwt-auth

  • Requires more setup and configuration compared to Sanctum
  • May have a steeper learning curve for developers new to JWT
  • Less integrated with Laravel's ecosystem

Code Comparison

jwt-auth:

$token = JWTAuth::attempt($credentials);
$user = JWTAuth::toUser($token);

Sanctum:

$user = User::where('email', $request->email)->first();
$token = $user->createToken('auth_token')->plainTextToken;

Key Differences

  • Sanctum is designed specifically for Laravel and offers seamless integration
  • jwt-auth provides more control over token structure and claims
  • Sanctum supports both token and session-based authentication
  • jwt-auth focuses solely on JWT-based authentication

Use Cases

  • Choose Sanctum for Laravel-specific projects with simple authentication needs
  • Opt for jwt-auth when working on cross-platform applications or requiring advanced JWT features

Community and Maintenance

  • Sanctum is officially maintained by the Laravel team
  • jwt-auth has a large community but may have less frequent updates

Performance

  • Sanctum generally has lower overhead due to its tight Laravel integration
  • jwt-auth may have slightly higher processing requirements for token validation

Laravel Passport provides OAuth2 server support to Laravel.

Pros of Passport

  • Full OAuth2 server implementation, supporting multiple grant types
  • Supports first-party and third-party API authentication
  • Provides built-in support for token scopes and refresh tokens

Cons of Passport

  • More complex setup and configuration
  • Heavier resource usage due to its comprehensive feature set
  • Steeper learning curve for developers new to OAuth2

Code Comparison

Passport (API token creation):

$token = $user->createToken('Token Name')->accessToken;

Sanctum (API token creation):

$token = $user->createToken('Token Name')->plainTextToken;

Summary

Passport is a full-featured OAuth2 server implementation, offering robust authentication for both first-party and third-party applications. It provides comprehensive features like token scopes and refresh tokens but comes with a more complex setup and higher resource usage.

Sanctum, on the other hand, is a lightweight authentication system designed primarily for first-party applications. It offers a simpler setup and lower resource usage, making it ideal for SPA (Single Page Applications) and mobile apps that don't require the full OAuth2 protocol.

The choice between Passport and Sanctum depends on the specific needs of your application. If you require full OAuth2 support or third-party API authentication, Passport is the way to go. For simpler authentication needs in first-party apps, Sanctum provides a more straightforward solution.

1,599

Backend controllers and scaffolding for Laravel authentication.

Pros of Fortify

  • Provides a complete authentication backend, including registration, password reset, and email verification
  • Offers two-factor authentication out of the box
  • Includes built-in views for authentication forms (can be published and customized)

Cons of Fortify

  • More opinionated and less flexible than Sanctum
  • Requires more setup and configuration for API authentication scenarios
  • May include unnecessary features for simple API-only applications

Code Comparison

Fortify (authentication action):

use Laravel\Fortify\Actions\AttemptToAuthenticate;

public function authenticate(Request $request)
{
    return app(AttemptToAuthenticate::class)(
        $request, $this->guard
    );
}

Sanctum (token creation):

use Laravel\Sanctum\HasApiTokens;

$token = $user->createToken('token-name');
return ['token' => $token->plainTextToken];

Fortify is a comprehensive authentication package that provides a full set of features for web and API authentication. It's ideal for applications that require a complete auth solution with minimal setup.

Sanctum, on the other hand, is a lightweight package focused on API token authentication and SPA authentication. It's more flexible and easier to integrate into existing applications or those with custom authentication requirements.

Choose Fortify for full-featured auth with less customization, or Sanctum for lightweight, flexible API authentication.

9,353

PHP package for JWT

Pros of php-jwt

  • Framework-agnostic, can be used with any PHP project
  • Lightweight and focused solely on JWT functionality
  • Simple to integrate and use without additional dependencies

Cons of php-jwt

  • Lacks built-in authentication and authorization features
  • Requires manual implementation of token storage and management
  • No out-of-the-box support for API token abilities or scopes

Code Comparison

Sanctum token creation:

$token = $user->createToken('token-name');

php-jwt token creation:

$payload = ['user_id' => $user->id];
$token = JWT::encode($payload, $secretKey, 'HS256');

Sanctum token validation:

$request->user()->tokenCan('ability');

php-jwt token validation:

$decoded = JWT::decode($token, new Key($secretKey, 'HS256'));

Summary

Sanctum is a comprehensive authentication system for Laravel, offering built-in features for API token management and SPA authentication. php-jwt, on the other hand, is a lightweight library focused solely on JWT encoding and decoding, providing more flexibility but requiring additional implementation for full authentication functionality.

9,325

A RESTful API package for the Laravel and Lumen frameworks.

Pros of Dingo API

  • More comprehensive API development toolkit with features like API versioning and rate limiting
  • Supports multiple authentication adapters (OAuth2, JWT, Basic Auth)
  • Offers built-in response transformers for data formatting

Cons of Dingo API

  • Less actively maintained compared to Sanctum
  • Steeper learning curve due to more complex features
  • May be overkill for simpler API projects

Code Comparison

Dingo API route definition:

$api = app('Dingo\Api\Routing\Router');

$api->version('v1', function ($api) {
    $api->get('users', 'App\Http\Controllers\UserController@index');
});

Sanctum route definition:

Route::middleware('auth:sanctum')->get('/user', function (Request $request) {
    return $request->user();
});

Dingo API focuses on versioning and more complex routing, while Sanctum provides a simpler approach for SPA authentication. Dingo API offers more features out of the box, but Sanctum integrates more seamlessly with Laravel's ecosystem and is actively maintained by the Laravel team.

Convert Figma logo designs to code with AI

Visual Copilot

Introducing Visual Copilot: A new AI model to turn Figma designs to high quality code using your components.

Try Visual Copilot

README

Logo Laravel Sanctum

Build Status Total Downloads Latest Stable Version License

Introduction

Laravel Sanctum provides a featherweight authentication system for SPAs and simple APIs.

Official Documentation

Documentation for Sanctum can be found on the Laravel website.

Contributing

Thank you for considering contributing to Sanctum! The contribution guide can be found in the Laravel documentation.

Code of Conduct

In order to ensure that the Laravel community is welcoming to all, please review and abide by the Code of Conduct.

Security Vulnerabilities

Please review our security policy on how to report security vulnerabilities.

License

Laravel Sanctum is open-sourced software licensed under the MIT license.