Building a Full OAuth2 Server with Laravel Passport
Overview of OAuth2 Implementation
External applications often need secure access to your user data without handling raw credentials.
Prerequisites and Toolkit
Before integrating Passport, ensure you have a solid grasp of
Key Libraries & Tools:
- Laravel Passport: The core package for issuing and managing OAuth2 tokens.
- Laravel Sanctum: A lighter alternative for first-party SPA or mobile authentication.
- Artisan CLI: Used for generating keys and running migrations.
Code Walkthrough: The Server Setup
To transform your user model into an OAuth2 provider, use the HasApiTokens trait. This adds the necessary methods to manage tokens and scopes directly on the user object.
use Laravel\Passport\HasApiTokens;
class User extends Authenticatable { use HasApiTokens, Notifiable; }
Passport manages state through several dedicated database tables created via migrations. These track `oauth_access_tokens` and `oauth_clients`. You must register a client—representing the third-party app—which generates a **Client ID** and **Client Secret**.
## The Client-Side Handshake
The consumer application, like a movie-tracking tool, must store these credentials in its `.env` file. During the flow, the client redirects the user to the main server's login page. Once authenticated, the server asks the user to grant specific permissions (scopes).
```javascript
// Typical environment configuration
OAUTH_CLIENT_ID=9
OAUTH_CLIENT_SECRET=your-secret-here
OAUTH_REDIRECT_URI=https://client-app.test/callback
Practical Use Cases
Consider an application named Sintop that stores movie watchlists. A third-party developer creates Cinema Wrapped to generate year-end statistics. By using Passport, the developer can request access to the user's movie list without ever seeing the user's password. This ecosystem encourages innovation while maintaining strict user privacy.
Tips and Syntax Notes
Always use redirect URI precisely as it appears in the database; even a trailing slash mismatch will cause the OAuth2 handshake to fail.
