Access tokens are a critical part of modern web applications, especially when it comes to API authentication. Laravel, one of the most popular PHP frameworks, provides robust tools for generating and managing access tokens. Whether you're building a complex OAuth2 server or a simple token-based authentication system, Laravel has you covered with Passport and Sanctum.
In this article, we’ll explore how Laravel generates access tokens, the differences between Passport and Sanctum, and how to implement them in your application.
What Are Access Tokens?
Access tokens are strings that represent a user’s authorization to access specific resources. They are commonly used in APIs to authenticate requests. When a user logs in or grants access to a client, the server generates an access token, which the client then includes in subsequent requests to prove their identity.
Laravel simplifies the process of generating and managing access tokens through two primary packages: Passport and Sanctum.
1. Generating Access Tokens with Laravel Passport
Laravel Passport is a full OAuth2 server implementation. It’s ideal for applications that require complex authentication scenarios, such as third-party API access or multi-client systems.
Steps to Generate Access Tokens with Passport
Step 1: Install Passport
To get started, install Passport via Composer:
composer require laravel/passport
Step 2: Run Migrations
Passport requires database tables to store OAuth2 tokens and clients. Run the migrations to create these tables:
php artisan migrate
Step 3: Install Passport
Generate encryption keys and create client credentials by running:
php artisan passport:install
This command creates client_id
and client_secret
pairs for your application.
Step 4: Configure API Authentication
In your AuthServiceProvider
, register Passport routes:
use Laravel\Passport\Passport;
public function boot()
{
$this->registerPolicies();
Passport::routes();
}
Step 5: Issue Access Tokens
To issue an access token, send a POST request to the /oauth/token
endpoint with the following parameters:
-
grant_type
: The type of grant (e.g.,password
,client_credentials
). -
client_id
: The client ID generated by Passport. -
client_secret
: The client secret generated by Passport. -
username
: The user’s email or username. -
password
: The user’s password. -
scope
: Optional scopes for the token.
Example request:
{
"grant_type": "password",
"client_id": "client-id",
"client_secret": "client-secret",
"username": "user@example.com",
"password": "password",
"scope": ""
}
Step 6: Receive the Token
The server responds with an access token and a refresh token:
{
"token_type": "Bearer",
"expires_in": 3600,
"access_token": "eyJ0eXAiOiJKV1QiLCJhbGciOiJSUzI1Ni...",
"refresh_token": "def50200e3b8a1a3c2c7d5e6f7a8b9c..."
}
2. Generating Access Tokens with Laravel Sanctum
Laravel Sanctum is a lightweight package designed for simple token-based authentication. It’s perfect for single-page applications (SPAs), mobile apps, or basic API authentication.
Steps to Generate Access Tokens with Sanctum
Step 1: Install Sanctum
Install Sanctum via Composer:
composer require laravel/sanctum
Step 2: Run Migrations
Sanctum requires a database table to store API tokens. Run the migrations to create this table:
php artisan migrate
Step 3: Configure Sanctum
Add Sanctum’s middleware to your api
middleware group in app/Http/Kernel.php
:
use Laravel\Sanctum\Http\Middleware\EnsureFrontendRequestsAreStateful;
'api' => [
EnsureFrontendRequestsAreStateful::class,
'throttle:api',
\Illuminate\Routing\Middleware\SubstituteBindings::class,
],
Step 4: Issue Access Tokens
After authenticating the user (e.g., via login), use the createToken
method to generate a token:
use Illuminate\Support\Facades\Auth;
$user = Auth::user();
$token = $user->createToken('token-name')->plainTextToken;
Step 5: Receive the Token
The createToken
method returns a plain-text token:
{
"token": "1|abcdef1234567890..."
}
Key Differences Between Passport and Sanctum
Feature | Passport | Sanctum |
---|---|---|
Use Case | Full OAuth2 implementation | Lightweight token-based auth |
Complexity | Suitable for complex systems | Simple and easy to use |
Token Management | Supports scopes, refresh tokens | Basic token management |
Performance | Slightly heavier due to OAuth2 | Lightweight and fast |
Ideal For | Third-party API access | SPAs, mobile apps, simple APIs |
Revoking Tokens
-
Passport: Tokens can be revoked using the
revoke
method or by deleting them from the database. -
Sanctum: Tokens can be revoked by deleting them from the
personal_access_tokens
table.
Conclusion
Laravel makes it easy to generate and manage access tokens for API authentication, whether you need a full OAuth2 implementation with Passport or a lightweight solution with Sanctum. By following the steps outlined in this article, you can implement secure and efficient token-based authentication in your Laravel application.
Choose Passport for complex OAuth2 scenarios and Sanctum for simpler, lightweight token-based authentication. Both tools are powerful and integrate seamlessly with Laravel, ensuring your application remains secure and scalable.
Happy coding!
Top comments (0)