> ## Documentation Index
> Fetch the complete documentation index at: https://kawax.biz/llms.txt
> Use this file to discover all available pages before exploring further.

# Laravel Passport (OAuth2-serverimplementatie)

> Uitleg over het implementeren van een OAuth2-server met Laravel Passport. Behandelt de keuze tussen Passport en Sanctum, installatie, clientbeheer, scopes en tokenbeheer.

## Wat is Passport

Laravel Passport is het officiële pakket om je Laravel-app als OAuth2-autorisatieserver te laten werken.
Je gebruikt het voor integraties met apps van derden of voor API's die een strikte OAuth2-flow vereisen.

```mermaid theme={null}
sequenceDiagram
    participant User as Gebruiker
    participant Client as OAuth-client
    participant App as Laravel-app<br>(Passport)
    participant API as Beveiligde API

    User->>Client: Start de koppeling
    Client->>App: Autorisatieverzoek
    App->>User: Toont toestemmingsscherm
    User->>App: Geeft toestemming
    App-->>Client: Autorisatiecode
    Client->>App: Wisselt autorisatiecode in voor access token
    App-->>Client: Access token
    Client->>API: API-aanroep met Bearer-token
    API-->>Client: Response
```

## Passport vs Sanctum

Is OAuth2 een vereiste, kies dan Passport.
Gaat het je om eenvoudige API-tokenauthenticatie of SPA-/mobiele authenticatie, kies dan Sanctum.

| Aspect             | Passport                                                                                       | Sanctum                                |
| ------------------ | ---------------------------------------------------------------------------------------------- | -------------------------------------- |
| Doel               | OAuth2-serverimplementatie                                                                     | Eenvoudige API-authenticatie           |
| Geschikte gevallen | Integratie met externe apps, naleving van de OAuth2-standaard, [MCP-server](/nl/mcp#oauth-2-1) | Eigen SPA, mobiel, persoonlijke tokens |
| Complexiteit       | Hoog                                                                                           | Laag                                   |

<Info>
  Als je een [MCP-server](/nl/mcp) bouwt die door AI-clients wordt benaderd, wordt officieel aanbevolen Passport te gebruiken. MCP-clients gaan namelijk doorgaans uit van authenticatie via OAuth.
</Info>

## Installatie

De officiële aanbeveling in Laravel 13 is `install:api --passport`.

```shell theme={null}
php artisan install:api --passport
```

Wil je het handmatig toevoegen aan een bestaand project, dan kun je het ook zo opzetten:

```shell theme={null}
composer require laravel/passport
php artisan passport:install
```

Bij de eerste deployment wil je soms alleen de sleutels genereren.

```shell theme={null}
php artisan passport:keys
```

## Configuratie

### Het User-model

Voeg de `HasApiTokens`-trait en de `OAuthenticatable`-interface toe aan het `User`-model.

```php theme={null}
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable;
use Laravel\Passport\Contracts\OAuthenticatable;
use Laravel\Passport\HasApiTokens;

class User extends Authenticatable implements OAuthenticatable
{
    use HasApiTokens, HasFactory, Notifiable;
}
```

### De auth-guard

Gebruik de `passport`-driver in de `api`-guard van `config/auth.php`.

```php theme={null}
'guards' => [
    'api' => [
        'driver' => 'passport',
        'provider' => 'users',
    ],
],
```

### Serviceproviderconfiguratie

In de `boot()` van de `AppServiceProvider` kun je scopedefinities en de geldigheidsduur van tokens instellen.

```php theme={null}
use Carbon\CarbonInterval;
use Laravel\Passport\Passport;

public function boot(): void
{
    Passport::tokensCan([
        'orders:read' => 'Bestellingen bekijken',
        'orders:create' => 'Bestellingen aanmaken',
    ]);

    Passport::defaultScopes(['orders:read']);

    Passport::tokensExpireIn(CarbonInterval::days(15));
    Passport::refreshTokensExpireIn(CarbonInterval::days(30));
    Passport::personalAccessTokensExpireIn(CarbonInterval::months(6));
}
```

## Clientbeheer

### Client voor de authorization code grant

```shell theme={null}
php artisan passport:client
```

Deze client gebruik je voor de standaard OAuth2-flow met een toestemmingsscherm voor de gebruiker.

### Client voor de client credentials grant

```shell theme={null}
php artisan passport:client --client
```

Voor endpoints voor machine-naar-machinecommunicatie gebruik je de `EnsureClientIsResourceOwner`-middleware.

```php theme={null}
use Laravel\Passport\Http\Middleware\EnsureClientIsResourceOwner;

Route::get('/orders', function () {
    // ...
})->middleware(EnsureClientIsResourceOwner::using('orders:read'));
```

## Tokenbeheer

### Scopes toekennen

```php theme={null}
$accessToken = $user->createToken(
    'dashboard-token',
    ['orders:read', 'orders:create']
)->accessToken;
```

### Scopes controleren

```php theme={null}
use Laravel\Passport\Http\Middleware\CheckToken;

Route::get('/orders', function () {
    // ...
})->middleware(['auth:api', CheckToken::using('orders:read')]);
```

### Intrekken

```php theme={null}
use Laravel\Passport\Passport;

$token = Passport::token()->find($tokenId);
$token?->revoke();
```

## API-routes beveiligen

Voorzie API's die je beveiligt met gebruikers-access-tokens van `auth:api`.

```php theme={null}
Route::middleware('auth:api')->group(function () {
    Route::get('/user', fn (Request $request) => $request->user());
    Route::get('/orders', [OrderController::class, 'index']);
});
```

<Warning>
  Gebruik voor routes met de client credentials grant niet `auth:api`, maar `EnsureClientIsResourceOwner`.
</Warning>

## Personal access tokens

Geschikt voor situaties waarin gebruikers zelf API-tokens uitgeven, zonder de volledige OAuth2-flow te gebruiken.

```shell theme={null}
php artisan passport:client --personal
```

```php theme={null}
$token = $request->user()->createToken('cli-token', ['orders:read'])->accessToken;
```

<Info>
  Als personal access tokens je hoofddoel zijn, wordt ook door Laravel zelf aanbevolen om Sanctum te overwegen.
</Info>

## Gerelateerde links

* [Officiële Laravel-documentatie: Passport](https://laravel.com/docs/13.x/passport)
* [Officiële Laravel-documentatie: Sanctum](https://laravel.com/docs/13.x/sanctum)


## Related topics

- [Laravel Sanctum (API-tokenauthenticatie)](/nl/sanctum.md)
- [Socialite (LINE Login) - LINE SDK for Laravel](/nl/packages/laravel-line-sdk/socialite.md)
- [Socialite for Discord](/nl/packages/socialite-discord.md)
- [LINE SDK for Laravel](/nl/packages/laravel-line-sdk/index.md)
- [Laravel Socialite (sociale authenticatie)](/nl/socialite.md)
