Top Related Projects
Associate users with roles and permissions
🔐 JSON Web Token Authentication for Laravel & Lumen
Laravel Sanctum provides a featherweight authentication system for SPAs and simple APIs.
A RESTful API package for the Laravel and Lumen frameworks.
Easily build Eloquent queries from API requests
Adds CORS (Cross-Origin Resource Sharing) headers support in your Laravel application
Quick Overview
Laravel Passport is an OAuth 2.0 authentication package for the Laravel framework. It provides a simple and secure way to implement authentication and authorization in your Laravel applications, allowing users to authenticate with your application using their own credentials or through third-party services like Google, Facebook, or GitHub.
Pros
- Seamless Integration with Laravel: Passport is designed to work seamlessly with the Laravel framework, making it easy to set up and configure within your existing Laravel application.
- Comprehensive OAuth 2.0 Implementation: Passport provides a full implementation of the OAuth 2.0 protocol, including support for authorization codes, implicit grants, and client credentials.
- Flexible Token Management: Passport allows you to manage access tokens, refresh tokens, and personal access tokens, providing a flexible and secure way to handle user authentication.
- Customizable Scopes: Passport supports the use of scopes, which allow you to define and manage the permissions granted to your application's users.
Cons
- Dependency on Laravel: Passport is tightly coupled with the Laravel framework, which means that it may not be suitable for use in non-Laravel applications.
- Complexity for Simple Use Cases: For simple authentication use cases, Passport may be overkill, and a simpler authentication solution may be more appropriate.
- Limited Documentation: While the Passport documentation is generally good, there may be some areas where the documentation could be more comprehensive or easier to understand.
- Potential Performance Impact: Depending on the size and complexity of your application, the use of Passport may have a slight performance impact due to the additional processing required for OAuth 2.0 authentication.
Code Examples
Here are a few examples of how to use Laravel Passport in your application:
- Registering a New Client:
$client = Passport::client()->create([
'name' => 'My Client',
'redirect' => 'http://example.com/callback',
'personal_access_client' => true,
'password_client' => true,
]);
This code creates a new OAuth 2.0 client for your application, which can be used to authenticate users and grant access tokens.
- Issuing an Access Token:
$token = $user->createToken('My Token')->accessToken;
This code creates a new access token for the authenticated user, which can be used to make authenticated requests to your application's API.
- Protecting a Route with Scopes:
Route::get('/profile', function () {
// This route is only accessible to users with the 'view-profile' scope
})->middleware('scopes:view-profile');
This code protects a route in your application, ensuring that only users with the view-profile
scope can access it.
Getting Started
To get started with Laravel Passport, follow these steps:
- Install the Passport package using Composer:
composer require laravel/passport
- Run the Passport installation command to set up the necessary database tables and configuration files:
php artisan passport:install
- Add the
Laravel\Passport\HasApiTokens
trait to yourApp\User
model:
use Laravel\Passport\HasApiTokens;
class User extends Authenticatable
{
use HasApiTokens, Notifiable;
// ...
}
- In your
config/auth.php
file, set thedriver
option for theapi
authentication guard topassport
:
'guards' => [
'web' => [
'driver' => 'session',
'provider' => 'users',
],
'api' => [
'driver' => 'passport',
'provider' => 'users',
],
],
- Finally, register the Passport routes in your
routes/web.php
file:
Route::middleware('auth:api')->get('/user', function (Request $request) {
return $request->user();
});
That's the basic setup for using Laravel Passport in your application. From here, you can explore the various features and functionality provided by Passport, such as creating clients, managing access tokens, and protecting your API routes.
Competitor Comparisons
Associate users with roles and permissions
Pros of Laravel Permission
- Simpler and more lightweight, focusing solely on role-based access control
- Easier to set up and use for basic permission management
- More flexible for custom permission structures
Cons of Laravel Permission
- Lacks built-in OAuth2 server functionality
- Does not provide API authentication out of the box
- May require additional packages for complex authentication scenarios
Code Comparison
Laravel Permission:
$user->givePermissionTo('edit articles');
$user->assignRole('writer');
if ($user->hasPermissionTo('edit articles')) {
// User can edit articles
}
Laravel Passport:
Route::middleware('auth:api')->get('/user', function (Request $request) {
return $request->user();
});
$user = $request->user();
if ($user->tokenCan('edit-articles')) {
// User can edit articles
}
Laravel Permission focuses on role and permission management within the application, while Laravel Passport provides OAuth2 server implementation for API authentication. Permission is more suitable for simple, role-based access control, whereas Passport is better for API-centric applications requiring robust authentication mechanisms. The choice between the two depends on the specific needs of your project, with Permission being easier to implement for basic authorization and Passport offering more comprehensive API authentication features.
🔐 JSON Web Token Authentication for Laravel & Lumen
Pros of jwt-auth
- Lightweight and focused solely on JWT implementation
- More flexible for custom token handling and claims
- Easier integration with non-Laravel backends or frontends
Cons of jwt-auth
- Less built-in features compared to Passport's full OAuth2 server
- Requires more manual configuration for advanced use cases
- Not officially supported by Laravel, potentially less long-term stability
Code Comparison
jwt-auth token generation:
$token = JWTAuth::fromUser($user);
Passport token generation:
$token = $user->createToken('Token Name')->accessToken;
Key Differences
- Passport provides a full OAuth2 server implementation, while jwt-auth focuses solely on JWT handling
- Passport integrates more seamlessly with Laravel's ecosystem and offers additional features like personal access tokens
- jwt-auth offers more flexibility for custom token handling and can be easier to integrate with non-Laravel systems
- Passport has official Laravel support, ensuring long-term compatibility and updates
Both libraries are popular choices for Laravel authentication, with the choice depending on specific project requirements, desired features, and integration needs.
Laravel Sanctum provides a featherweight authentication system for SPAs and simple APIs.
Pros of Sanctum
- Lightweight and simple to implement
- Built-in support for SPA authentication
- Easier to set up and maintain for smaller projects
Cons of Sanctum
- Limited token customization options
- Lacks some advanced features like token scopes and refresh tokens
Code Comparison
Sanctum token creation:
$token = $user->createToken('token-name');
Passport token creation:
$token = $user->createToken('token-name', ['scope1', 'scope2'])->accessToken;
Summary
Sanctum is a lightweight authentication package for Laravel, ideal for simple APIs and SPAs. It's easier to set up and maintain compared to Passport, but lacks some advanced features.
Passport, on the other hand, is a full OAuth2 server implementation, offering more robust features like token scopes and refresh tokens. It's better suited for larger, more complex applications that require fine-grained access control.
Choose Sanctum for simpler projects or when you need SPA authentication out of the box. Opt for Passport when you need a full-featured OAuth2 server or advanced token management capabilities.
A RESTful API package for the Laravel and Lumen frameworks.
Pros of Dingo API
- More flexible and customizable API structure
- Built-in API versioning support
- Comprehensive rate limiting and throttling features
Cons of Dingo API
- Less active maintenance and community support
- Steeper learning curve for beginners
- May require more setup and configuration
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');
});
Passport route definition:
Route::middleware('auth:api')->get('/user', function (Request $request) {
return $request->user();
});
Key Differences
- Dingo API focuses on building comprehensive API structures with versioning and advanced features
- Passport specializes in OAuth2 authentication and token management
- Dingo API requires more manual setup, while Passport integrates seamlessly with Laravel's authentication system
- Passport has more frequent updates and better documentation
- Dingo API offers more control over API responses and transformations
Use Cases
- Choose Dingo API for complex, version-controlled APIs with custom response formats
- Opt for Passport when prioritizing OAuth2 authentication and simpler API setups within the Laravel ecosystem
Community and Support
- Passport has a larger user base and more frequent updates
- Dingo API has a smaller but dedicated community, with less frequent maintenance
Easily build Eloquent queries from API requests
Pros of Laravel Query Builder
- Simplifies complex query building for API endpoints
- Allows for easy filtering, sorting, and including relations
- Lightweight and focused on query manipulation
Cons of Laravel Query Builder
- Limited to query building, doesn't handle authentication
- Requires additional setup for API authentication and authorization
- May not be suitable for complex OAuth2 scenarios
Code Comparison
Laravel Query Builder:
use Spatie\QueryBuilder\QueryBuilder;
$users = QueryBuilder::for(User::class)
->allowedFilters(['name', 'email'])
->allowedSorts(['name', 'created_at'])
->paginate();
Passport:
use Laravel\Passport\HasApiTokens;
class User extends Authenticatable
{
use HasApiTokens;
}
// In AuthServiceProvider
Passport::routes();
Summary
Laravel Query Builder focuses on simplifying API query building, offering easy filtering and sorting. It's lightweight but doesn't handle authentication. Passport, on the other hand, provides full OAuth2 server implementation for Laravel, managing API authentication and authorization. While Query Builder enhances data retrieval, Passport secures API access. The choice depends on whether you need query manipulation (Query Builder) or robust API authentication (Passport).
Adds CORS (Cross-Origin Resource Sharing) headers support in your Laravel application
Pros of Laravel CORS
- Lightweight and focused solely on handling CORS
- Easy to configure and integrate into existing Laravel applications
- Provides fine-grained control over CORS settings
Cons of Laravel CORS
- Limited in scope, only handles CORS-related functionality
- Requires additional packages for authentication and API token management
Code Comparison
Laravel CORS configuration:
return [
'paths' => ['api/*'],
'allowed_methods' => ['*'],
'allowed_origins' => ['*'],
'allowed_origins_patterns' => [],
'allowed_headers' => ['*'],
'exposed_headers' => [],
'max_age' => 0,
'supports_credentials' => false,
];
Passport route definition:
Route::middleware('auth:api')->get('/user', function (Request $request) {
return $request->user();
});
Summary
Laravel CORS is a specialized package for handling Cross-Origin Resource Sharing in Laravel applications. It's lightweight and easy to configure but focuses solely on CORS functionality. Passport, on the other hand, is a full-featured OAuth2 server implementation for Laravel, providing robust authentication and API token management. While Laravel CORS excels in its specific domain, Passport offers a more comprehensive solution for API authentication and authorization.
Convert designs to code with AI
Introducing Visual Copilot: A new AI model to turn Figma designs to high quality code using your components.
Try Visual CopilotREADME
Introduction
Laravel Passport is an OAuth2 server and API authentication package that is simple and enjoyable to use.
Official Documentation
Documentation for Passport can be found on the Laravel website.
Contributing
Thank you for considering contributing to Passport! 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 Passport is open-sourced software licensed under the MIT license.
Top Related Projects
Associate users with roles and permissions
🔐 JSON Web Token Authentication for Laravel & Lumen
Laravel Sanctum provides a featherweight authentication system for SPAs and simple APIs.
A RESTful API package for the Laravel and Lumen frameworks.
Easily build Eloquent queries from API requests
Adds CORS (Cross-Origin Resource Sharing) headers support in your Laravel application
Convert designs to code with AI
Introducing Visual Copilot: A new AI model to turn Figma designs to high quality code using your components.
Try Visual Copilot