Deps: Add passport

This commit is contained in:
= 2026-06-16 11:46:56 +00:00
parent dfb47f7d19
commit ce209cd14d
16 changed files with 1639 additions and 11 deletions

View File

@ -0,0 +1,205 @@
---
name: passport-development
description: "Develops OAuth2 API authentication with Laravel Passport. Activates when installing or configuring Passport; setting up OAuth2 grants (authorization code, client credentials, personal access tokens, device authorization); managing OAuth clients; protecting API routes with token authentication; defining or checking token scopes; configuring SPA cookie authentication; handling token lifetimes and refresh tokens; or when the user mentions Passport, OAuth2, API tokens, bearer tokens, or API authentication. Make sure to use this skill whenever the user works with OAuth2, API tokens, or third-party API access, even if they don't explicitly mention Passport."
license: MIT
metadata:
author: laravel
---
# Passport OAuth2 Authentication
## Documentation First
**Always use `search-docs` before writing Passport code.** The documentation covers every grant type, configuration option, and edge case in detail. This skill teaches you how to navigate Passport — the docs have the implementation specifics.
```
search-docs(queries: ["Passport installation"], packages: ["laravel/framework@12.x"])
```
The Passport docs live under the `laravel/framework` package — not `laravel/passport`.
## When to Apply
Activate this skill when:
- Installing or configuring Passport
- Setting up OAuth2 authorization grants
- Creating or managing OAuth clients
- Protecting API routes with token authentication
- Defining or checking token scopes
- Configuring SPA cookie-based authentication
- Choosing between Passport and Sanctum
## Passport vs. Sanctum
**Passport** is a full OAuth2 server — use it when third-party applications need to consume your API and when you need OAuth2 authorization code grants, client credentials for machine-to-machine auth, or device authorization flow.
**Sanctum** is simpler — use it when first-party SPAs, third parties, or mobile apps consume the API but you don't need the full OAuth2 grant flows.
## Installation
Three steps are always required:
### 1. Install Passport
```bash
php artisan install:api --passport
```
This publishes migrations, generates encryption keys, and registers routes.
### 2. Configure the User model
The User model needs both the `HasApiTokens` trait AND the `OAuthenticatable` interface. Missing the interface is the most common Passport setup mistake — it causes runtime errors that can be confusing to debug.
```php
use Laravel\Passport\Contracts\OAuthenticatable;
use Laravel\Passport\HasApiTokens;
class User extends Authenticatable implements OAuthenticatable
{
use HasApiTokens;
}
```
### 3. Configure the auth guard
The `api` guard must use the `passport` driver in `config/auth.php`. Using `token` or `sanctum` here silently breaks Passport authentication.
```php
'guards' => [
'api' => [
'driver' => 'passport',
'provider' => 'users',
],
],
```
## Choosing a Grant Type
Matching the right grant to the use case is the most important Passport decision. Use `search-docs` for implementation details of any grant.
| Use Case | Grant Type | Client Flag |
|----------|-----------|-------------|
| Third-party app accessing user data | Authorization Code | (default) |
| Mobile/SPA without client secret | Authorization Code + PKCE | `--public` |
| Machine-to-machine, no user context | Client Credentials | `--client` |
| User-generated API keys | Personal Access Tokens | `--personal` |
| Smart TV, CLI, IoT devices | Device Authorization | `--device` |
**Legacy grants** (Password, Implicit) are disabled by default and not recommended. They must be explicitly enabled with `Passport::enablePasswordGrant()` or `Passport::enableImplicitGrant()`.
## Client Management
Create clients with the appropriate flag for the grant type:
```bash
php artisan passport:client # Authorization code
php artisan passport:client --public # PKCE (no secret)
php artisan passport:client --client # Client credentials
php artisan passport:client --personal # Personal access tokens
php artisan passport:client --device # Device authorization
```
Additional flags: `--name=`, `--redirect_uri=`, `--provider=`.
Client secrets are hashed by default — the plain-text secret is only shown at creation time and cannot be retrieved later.
## Protecting Routes
Apply `auth:api` middleware. Clients send tokens via the `Authorization: Bearer <token>` header.
```php
Route::get('/user', function (Request $request) {
return $request->user();
})->middleware('auth:api');
```
### Scope Enforcement
Scope middleware must come alongside `auth:api`:
- `CheckToken::using('scope1', 'scope2')` — requires ALL listed scopes
- `CheckTokenForAnyScope::using('scope1', 'scope2')` — requires ANY listed scope
- `EnsureClientIsResourceOwner::using('scope1')` — restricts to client credential tokens
```php
use Laravel\Passport\Http\Middleware\CheckToken;
Route::get('/orders', function () {
// ...
})->middleware(['auth:api', CheckToken::using('orders:read')]);
```
### Programmatic scope checking
```php
if ($request->user()->tokenCan('place-orders')) {
// ...
}
```
Use `search-docs` for full scope middleware registration and usage patterns.
## Key Configuration
Configure in `AppServiceProvider::boot()`. Use `search-docs` for the full list of options.
```php
// Token lifetimes (each is independent)
Passport::tokensExpireIn(now()->addDays(15));
Passport::refreshTokensExpireIn(now()->addDays(30));
Passport::personalAccessTokensExpireIn(now()->addMonths(6));
// Define scopes
Passport::tokensCan([
'place-orders' => 'Place orders',
'check-status' => 'Check order status',
]);
```
## SPA Cookie Authentication
For first-party SPAs, the `CreateFreshApiToken` middleware issues a `laravel_token` cookie containing an encrypted JWT. The SPA must include CSRF tokens — missing the `X-CSRF-TOKEN` or `X-XSRF-TOKEN` header causes 419 errors.
Use `search-docs` for setup details — this feature has specific CSRF and cookie configuration requirements.
## Testing
Passport provides helpers to bypass full OAuth flows in tests:
```php
Passport::actingAs($user, ['scope1', 'scope2']);
Passport::actingAsClient($client, ['scope1']);
```
## Token Maintenance
```bash
php artisan passport:purge # Purge revoked & expired
php artisan passport:purge --revoked # Only revoked
php artisan passport:purge --expired # Only expired
```
Schedule `passport:purge` for regular expired token clean-up.
## Events
All in `Laravel\Passport\Events`: `AccessTokenCreated`, `AccessTokenRevoked`, `RefreshTokenCreated`.
## Common Pitfalls
- **Missing `OAuthenticatable` interface** — both the `HasApiTokens` trait and the `OAuthenticatable` interface are required on the User model. Missing the interface causes runtime errors.
- **Wrong guard driver** — the `api` guard must use `passport`, not `token` or `sanctum`. This fails silently.
- **Token lifetime confusion** — access token, refresh token, and personal access token lifetimes are all independent settings.
- **Missing CSRF for SPA cookie auth**`CreateFreshApiToken` requires CSRF tokens. Use `Passport::ignoreCsrfToken()` only if you understand the security implications.
- **Client secrets are hashed** — the plain-text secret is only available at creation time.
- **Legacy grants are disabled** — Password and Implicit grants must be explicitly enabled and are not recommended.

View File

@ -0,0 +1,205 @@
---
name: passport-development
description: "Develops OAuth2 API authentication with Laravel Passport. Activates when installing or configuring Passport; setting up OAuth2 grants (authorization code, client credentials, personal access tokens, device authorization); managing OAuth clients; protecting API routes with token authentication; defining or checking token scopes; configuring SPA cookie authentication; handling token lifetimes and refresh tokens; or when the user mentions Passport, OAuth2, API tokens, bearer tokens, or API authentication. Make sure to use this skill whenever the user works with OAuth2, API tokens, or third-party API access, even if they don't explicitly mention Passport."
license: MIT
metadata:
author: laravel
---
# Passport OAuth2 Authentication
## Documentation First
**Always use `search-docs` before writing Passport code.** The documentation covers every grant type, configuration option, and edge case in detail. This skill teaches you how to navigate Passport — the docs have the implementation specifics.
```
search-docs(queries: ["Passport installation"], packages: ["laravel/framework@12.x"])
```
The Passport docs live under the `laravel/framework` package — not `laravel/passport`.
## When to Apply
Activate this skill when:
- Installing or configuring Passport
- Setting up OAuth2 authorization grants
- Creating or managing OAuth clients
- Protecting API routes with token authentication
- Defining or checking token scopes
- Configuring SPA cookie-based authentication
- Choosing between Passport and Sanctum
## Passport vs. Sanctum
**Passport** is a full OAuth2 server — use it when third-party applications need to consume your API and when you need OAuth2 authorization code grants, client credentials for machine-to-machine auth, or device authorization flow.
**Sanctum** is simpler — use it when first-party SPAs, third parties, or mobile apps consume the API but you don't need the full OAuth2 grant flows.
## Installation
Three steps are always required:
### 1. Install Passport
```bash
php artisan install:api --passport
```
This publishes migrations, generates encryption keys, and registers routes.
### 2. Configure the User model
The User model needs both the `HasApiTokens` trait AND the `OAuthenticatable` interface. Missing the interface is the most common Passport setup mistake — it causes runtime errors that can be confusing to debug.
```php
use Laravel\Passport\Contracts\OAuthenticatable;
use Laravel\Passport\HasApiTokens;
class User extends Authenticatable implements OAuthenticatable
{
use HasApiTokens;
}
```
### 3. Configure the auth guard
The `api` guard must use the `passport` driver in `config/auth.php`. Using `token` or `sanctum` here silently breaks Passport authentication.
```php
'guards' => [
'api' => [
'driver' => 'passport',
'provider' => 'users',
],
],
```
## Choosing a Grant Type
Matching the right grant to the use case is the most important Passport decision. Use `search-docs` for implementation details of any grant.
| Use Case | Grant Type | Client Flag |
|----------|-----------|-------------|
| Third-party app accessing user data | Authorization Code | (default) |
| Mobile/SPA without client secret | Authorization Code + PKCE | `--public` |
| Machine-to-machine, no user context | Client Credentials | `--client` |
| User-generated API keys | Personal Access Tokens | `--personal` |
| Smart TV, CLI, IoT devices | Device Authorization | `--device` |
**Legacy grants** (Password, Implicit) are disabled by default and not recommended. They must be explicitly enabled with `Passport::enablePasswordGrant()` or `Passport::enableImplicitGrant()`.
## Client Management
Create clients with the appropriate flag for the grant type:
```bash
php artisan passport:client # Authorization code
php artisan passport:client --public # PKCE (no secret)
php artisan passport:client --client # Client credentials
php artisan passport:client --personal # Personal access tokens
php artisan passport:client --device # Device authorization
```
Additional flags: `--name=`, `--redirect_uri=`, `--provider=`.
Client secrets are hashed by default — the plain-text secret is only shown at creation time and cannot be retrieved later.
## Protecting Routes
Apply `auth:api` middleware. Clients send tokens via the `Authorization: Bearer <token>` header.
```php
Route::get('/user', function (Request $request) {
return $request->user();
})->middleware('auth:api');
```
### Scope Enforcement
Scope middleware must come alongside `auth:api`:
- `CheckToken::using('scope1', 'scope2')` — requires ALL listed scopes
- `CheckTokenForAnyScope::using('scope1', 'scope2')` — requires ANY listed scope
- `EnsureClientIsResourceOwner::using('scope1')` — restricts to client credential tokens
```php
use Laravel\Passport\Http\Middleware\CheckToken;
Route::get('/orders', function () {
// ...
})->middleware(['auth:api', CheckToken::using('orders:read')]);
```
### Programmatic scope checking
```php
if ($request->user()->tokenCan('place-orders')) {
// ...
}
```
Use `search-docs` for full scope middleware registration and usage patterns.
## Key Configuration
Configure in `AppServiceProvider::boot()`. Use `search-docs` for the full list of options.
```php
// Token lifetimes (each is independent)
Passport::tokensExpireIn(now()->addDays(15));
Passport::refreshTokensExpireIn(now()->addDays(30));
Passport::personalAccessTokensExpireIn(now()->addMonths(6));
// Define scopes
Passport::tokensCan([
'place-orders' => 'Place orders',
'check-status' => 'Check order status',
]);
```
## SPA Cookie Authentication
For first-party SPAs, the `CreateFreshApiToken` middleware issues a `laravel_token` cookie containing an encrypted JWT. The SPA must include CSRF tokens — missing the `X-CSRF-TOKEN` or `X-XSRF-TOKEN` header causes 419 errors.
Use `search-docs` for setup details — this feature has specific CSRF and cookie configuration requirements.
## Testing
Passport provides helpers to bypass full OAuth flows in tests:
```php
Passport::actingAs($user, ['scope1', 'scope2']);
Passport::actingAsClient($client, ['scope1']);
```
## Token Maintenance
```bash
php artisan passport:purge # Purge revoked & expired
php artisan passport:purge --revoked # Only revoked
php artisan passport:purge --expired # Only expired
```
Schedule `passport:purge` for regular expired token clean-up.
## Events
All in `Laravel\Passport\Events`: `AccessTokenCreated`, `AccessTokenRevoked`, `RefreshTokenCreated`.
## Common Pitfalls
- **Missing `OAuthenticatable` interface** — both the `HasApiTokens` trait and the `OAuthenticatable` interface are required on the User model. Missing the interface causes runtime errors.
- **Wrong guard driver** — the `api` guard must use `passport`, not `token` or `sanctum`. This fails silently.
- **Token lifetime confusion** — access token, refresh token, and personal access token lifetimes are all independent settings.
- **Missing CSRF for SPA cookie auth**`CreateFreshApiToken` requires CSRF tokens. Use `Passport::ignoreCsrfToken()` only if you understand the security implications.
- **Client secrets are hashed** — the plain-text secret is only available at creation time.
- **Legacy grants are disabled** — Password and Implicit grants must be explicitly enabled and are not recommended.

View File

@ -9,9 +9,10 @@ ## Foundational Context
This application is a Laravel application and its main Laravel ecosystems package & versions are below. You are an expert with them all. Ensure you abide by these specific packages & versions.
- php - 8.4
- php - 8.5
- laravel/fortify (FORTIFY) - v1
- laravel/framework (LARAVEL) - v13
- laravel/passport (PASSPORT) - v13
- laravel/prompts (PROMPTS) - v0
- livewire/flux (FLUXUI_FREE) - v2
- livewire/livewire (LIVEWIRE) - v4

View File

@ -9,9 +9,10 @@ ## Foundational Context
This application is a Laravel application and its main Laravel ecosystems package & versions are below. You are an expert with them all. Ensure you abide by these specific packages & versions.
- php - 8.4
- php - 8.5
- laravel/fortify (FORTIFY) - v1
- laravel/framework (LARAVEL) - v13
- laravel/passport (PASSPORT) - v13
- laravel/prompts (PROMPTS) - v0
- livewire/flux (FLUXUI_FREE) - v2
- livewire/livewire (LIVEWIRE) - v4

View File

@ -12,6 +12,7 @@
"skills": [
"fortify-development",
"laravel-best-practices",
"passport-development",
"fluxui-development",
"livewire-development",
"pest-testing",

View File

@ -8,6 +8,7 @@
return Application::configure(basePath: dirname(__DIR__))
->withRouting(
web: __DIR__.'/../routes/web.php',
api: __DIR__.'/../routes/api.php',
commands: __DIR__.'/../routes/console.php',
health: '/up',
)

View File

@ -10,9 +10,14 @@
"license": "MIT",
"require": {
"php": "^8.3",
"ext-dom": "*",
"ext-libxml": "*",
"ext-openssl": "*",
"ext-zlib": "*",
"gehrisandro/tailwind-merge-laravel": "^1.4",
"laravel/fortify": "^1.34",
"laravel/framework": "^13.7",
"laravel/passport": "^13.0",
"laravel/tinker": "^3.0",
"livewire/flux": "^2.13.1",
"livewire/livewire": "^4.3",
@ -21,11 +26,7 @@
"robsontenorio/mary": "^2.8",
"spatie/laravel-activitylog": "^5.0",
"spatie/laravel-data": "^4.22",
"spatie/laravel-permission": "^7.4",
"ext-openssl": "*",
"ext-zlib": "*",
"ext-dom": "*",
"ext-libxml": "*"
"spatie/laravel-permission": "^7.4"
},
"require-dev": {
"captainhook/captainhook": "^5.29",

948
composer.lock generated

File diff suppressed because it is too large Load Diff

View File

@ -44,6 +44,10 @@
'driver' => 'session',
'provider' => 'users',
],
'api' => [
'driver' => 'passport',
'provider' => 'users',
],
],
/*

50
config/passport.php Normal file
View File

@ -0,0 +1,50 @@
<?php
declare(strict_types=1);
return [
/*
|--------------------------------------------------------------------------
| Passport Guard
|--------------------------------------------------------------------------
|
| Here you may specify which authentication guard Passport will use when
| authenticating users. This value should correspond with one of your
| guards that is already present in your "auth" configuration file.
|
*/
'guard' => 'web',
'middleware' => [],
/*
|--------------------------------------------------------------------------
| Encryption Keys
|--------------------------------------------------------------------------
|
| Passport uses encryption keys while generating secure access tokens for
| your application. By default, the keys are stored as local files but
| can be set via environment variables when that is more convenient.
|
*/
'private_key' => env('PASSPORT_PRIVATE_KEY'),
'public_key' => env('PASSPORT_PUBLIC_KEY'),
/*
|--------------------------------------------------------------------------
| Passport Database Connection
|--------------------------------------------------------------------------
|
| By default, Passport's models will utilize your application's default
| database connection. If you wish to use a different connection you
| may specify the configured name of the database connection here.
|
*/
'connection' => env('PASSPORT_CONNECTION'),
];

View File

@ -0,0 +1,41 @@
<?php
declare(strict_types=1);
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
return new class() extends Migration
{
/**
* Run the migrations.
*/
public function up(): void
{
Schema::create('oauth_auth_codes', function (Blueprint $table): void {
$table->char('id', 80)->primary();
$table->foreignId('user_id')->index();
$table->foreignUuid('client_id');
$table->text('scopes')->nullable();
$table->boolean('revoked');
$table->dateTime('expires_at')->nullable();
});
}
/**
* Reverse the migrations.
*/
public function down(): void
{
Schema::dropIfExists('oauth_auth_codes');
}
/**
* Get the migration connection name.
*/
public function getConnection(): ?string
{
return $this->connection ?? config('passport.connection');
}
};

View File

@ -0,0 +1,43 @@
<?php
declare(strict_types=1);
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
return new class() extends Migration
{
/**
* Run the migrations.
*/
public function up(): void
{
Schema::create('oauth_access_tokens', function (Blueprint $table): void {
$table->char('id', 80)->primary();
$table->foreignId('user_id')->nullable()->index();
$table->foreignUuid('client_id');
$table->string('name')->nullable();
$table->text('scopes')->nullable();
$table->boolean('revoked');
$table->timestamps();
$table->dateTime('expires_at')->nullable();
});
}
/**
* Reverse the migrations.
*/
public function down(): void
{
Schema::dropIfExists('oauth_access_tokens');
}
/**
* Get the migration connection name.
*/
public function getConnection(): ?string
{
return $this->connection ?? config('passport.connection');
}
};

View File

@ -0,0 +1,39 @@
<?php
declare(strict_types=1);
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
return new class() extends Migration
{
/**
* Run the migrations.
*/
public function up(): void
{
Schema::create('oauth_refresh_tokens', function (Blueprint $table): void {
$table->char('id', 80)->primary();
$table->char('access_token_id', 80)->index();
$table->boolean('revoked');
$table->dateTime('expires_at')->nullable();
});
}
/**
* Reverse the migrations.
*/
public function down(): void
{
Schema::dropIfExists('oauth_refresh_tokens');
}
/**
* Get the migration connection name.
*/
public function getConnection(): ?string
{
return $this->connection ?? config('passport.connection');
}
};

View File

@ -0,0 +1,44 @@
<?php
declare(strict_types=1);
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
return new class() extends Migration
{
/**
* Run the migrations.
*/
public function up(): void
{
Schema::create('oauth_clients', function (Blueprint $table): void {
$table->uuid('id')->primary();
$table->nullableMorphs('owner');
$table->string('name');
$table->string('secret')->nullable();
$table->string('provider')->nullable();
$table->text('redirect_uris');
$table->text('grant_types');
$table->boolean('revoked');
$table->timestamps();
});
}
/**
* Reverse the migrations.
*/
public function down(): void
{
Schema::dropIfExists('oauth_clients');
}
/**
* Get the migration connection name.
*/
public function getConnection(): ?string
{
return $this->connection ?? config('passport.connection');
}
};

View File

@ -0,0 +1,44 @@
<?php
declare(strict_types=1);
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
return new class() extends Migration
{
/**
* Run the migrations.
*/
public function up(): void
{
Schema::create('oauth_device_codes', function (Blueprint $table): void {
$table->char('id', 80)->primary();
$table->foreignId('user_id')->nullable()->index();
$table->foreignUuid('client_id')->index();
$table->char('user_code', 8)->unique();
$table->text('scopes');
$table->boolean('revoked');
$table->dateTime('user_approved_at')->nullable();
$table->dateTime('last_polled_at')->nullable();
$table->dateTime('expires_at')->nullable();
});
}
/**
* Reverse the migrations.
*/
public function down(): void
{
Schema::dropIfExists('oauth_device_codes');
}
/**
* Get the migration connection name.
*/
public function getConnection(): ?string
{
return $this->connection ?? config('passport.connection');
}
};

8
routes/api.php Normal file
View File

@ -0,0 +1,8 @@
<?php
declare(strict_types=1);
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Route;
Route::get('/user', fn (Request $request) => $request->user())->middleware('auth:api');