Laravel Passport: A Complete Tutorial and Example Build

Master OAuth2 API authentication with Laravel Passport. This comprehensive guide covers installation, configuration, client creation, and production deployment.

Understanding OAuth2 and Laravel Passport

Before diving into the implementation details, it is important to understand what OAuth2 is and why it matters for your API authentication strategy. OAuth2 is an authorization framework that enables applications to obtain limited access to user accounts on an HTTP service. It works by delegating user authentication to the service that hosts the user account, authorizing third-party applications to access that account without requiring the user to share their credentials directly.

Laravel Passport brings the full power of OAuth2 to your Laravel application without requiring you to understand the complex cryptographic operations that underlie the protocol. The package automatically creates the database tables needed to store OAuth clients, access tokens, and refresh tokens. It also provides a convenient artisan command that generates the encryption keys required for JWT token signing. Once installed, Passport registers routes for token issuance, refresh, and revocation that you can customize according to your application's needs.

The package supports multiple grant types, including the Authorization Code grant for web applications, the Password grant for first-party mobile applications, the Client Credentials grant for machine-to-machine communication, and the Implicit grant for JavaScript applications.

If you're building a full-stack web application with API endpoints, implementing proper authentication from the start is essential for long-term security and scalability. For teams exploring API development solutions, understanding OAuth2 fundamentals is a critical skill that transfers across technology stacks.

What Laravel Passport Provides

Complete OAuth2 Server

Full implementation of OAuth2 protocol including token issuance, refresh, and revocation.

Multiple Grant Types

Support for Authorization Code, Password, Client Credentials, and Personal Access grants.

JWT Token Support

Secure token generation and validation using industry-standard JWT format.

Database Integration

Automatic table creation for OAuth clients, tokens, and refresh tokens.

Scope Management

Fine-grained access control through OAuth2 scopes and permissions.

API Route Protection

Simple middleware for protecting your API endpoints with bearer token authentication.

Installation and Initial Setup

The installation process for Laravel Passport is straightforward, but it is important to ensure that your environment meets the prerequisites before you begin. Laravel Passport requires Laravel 10 or 11, PHP 8.1 or higher, and a database supported by Laravel such as MySQL, PostgreSQL, or SQLite.

Step 1: Install via Composer

composer require laravel/passport

Step 2: Run Passport Install

php artisan passport:install

This command generates encryption keys, creates client records, and runs database migrations. The encryption keys are stored in the storage directory and should be backed up along with your application code.

Step 3: Configure the User Model

In your User model, add the HasApiTokens trait:

use Laravel\Passport\HasApiTokens;

class User extends Authenticatable
{
 use HasApiTokens, Notifiable;
}

Step 4: Update Authentication Config

In config/auth.php, set the api driver to passport:

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

Step 5: Register Passport Routes

In AuthServiceProvider.php, call the routes method:

use Laravel\Passport\Passport;

public function boot()
{
 $this->registerPolicies();
 Passport::routes();
}

For enterprise-grade API security, implementing OAuth2 with Laravel Passport provides a robust foundation that scales with your application needs. Understanding these API development fundamentals will help you build secure, scalable systems.

Creating OAuth Clients

OAuth clients represent applications that will use your API. Each client has a unique identifier and secret that are used during the token exchange process.

Password Grant Client

For first-party mobile applications where users enter credentials directly:

php artisan passport:client --password

Client Credentials Client

For machine-to-machine communication without user involvement:

php artisan passport:client --client

Personal Access Client

For testing and development purposes:

php artisan passport:client --personal

Each client creation outputs a Client ID and Client Secret. Store these securely as they are only displayed once during creation.

When designing your API architecture, proper client management is crucial for maintaining security while enabling seamless integration with third-party services. This approach aligns with broader web development best practices for building secure, maintainable applications.

Obtaining Access Token with Client Credentials
1curl -X POST "http://localhost/oauth/token" \2 -H "Content-Type: application/json" \3 -d '{4 "grant_type": "client_credentials",5 "client_id": "YOUR_CLIENT_ID",6 "client_secret": "YOUR_CLIENT_SECRET"7 }'
Token Response
1{2 "token_type": "Bearer",3 "expires_in": 31536000,4 "access_token": "eyJ0eXA..."5}

Protecting Your API Routes

Once Passport is configured, you can protect your API routes using the auth:api middleware:

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

Using the Access Token

curl -H "Authorization: Bearer ACCESS_TOKEN_HERE" http://localhost/api/user

Or with Laravel's HTTP client:

$response = Http::withToken($accessToken)->get('http://localhost/api/user');

Proper API security requires defense-in-depth approaches, with OAuth2 authentication serving as a critical layer in protecting your application's sensitive endpoints and data. When building web applications that expose APIs, implementing robust authentication from day one is essential for long-term success.

Advanced Configuration and Customization

Token Expiration Settings

Configure token lifetimes in AuthServiceProvider:

Passport::tokensExpireIn(now()->addHours(1));
Passport::refreshTokensExpireIn(now()->addDays(30));

Defining Scopes

Passport::tokensCan([
 'read' => 'Read-only access',
 'write' => 'Write access',
 'admin' => 'Administrative access',
]);

Revoking Tokens

$user->token()->revoke();

Conclusion

Laravel Passport provides a powerful and flexible solution for implementing OAuth2 authentication in your Laravel applications. By following this guide, you can set up a complete OAuth2 server that supports multiple client types, protects your API endpoints, and integrates seamlessly with your existing Laravel application.

Implementing proper API authentication is essential for any modern web application that exposes services to external clients or mobile applications. Laravel Passport handles the complexity of OAuth2 implementation, allowing you to focus on building your application's core functionality while maintaining enterprise-grade security standards. For organizations seeking comprehensive API security solutions, partnering with experienced developers ensures your authentication infrastructure meets industry standards and scales with your business needs.

Frequently Asked Questions

Ready to Secure Your Laravel API?

Our team of Laravel experts can help you implement secure OAuth2 authentication for your application.

Sources

  1. Laravel Passport Documentation - Official Laravel documentation for OAuth2 server implementation
  2. LogRocket: Laravel Passport Tutorial - Practical implementation guide with code examples
  3. DevOpsSchool: Complete Guide of Laravel Passport - Comprehensive setup and troubleshooting reference