Ontwikkel een RESTful API met Laravel Passport voor OAuth2 Authenticatie
description
Met deze prompt kan de gebruiker een veilige, gestandaardiseerde authenticatie implementeren voor zijn Laravel API met behulp van Laravel Passport. Dit verbetert de beveiliging door het gebruik van OAuth2 tokens en maakt de API geschikt voor externe clients en mobiele apps. Het biedt een duidelijk stappenplan, wat het eenvoudiger maakt dan zelf uitzoeken hoe OAuth2 in Laravel werkt.
prompt
Help me een RESTful API te ontwikkelen met Laravel die OAuth2 authenticatie gebruikt via Laravel Passport. Mijn API onderwerp is: <beschrijf het onderwerp van je API>. Leg uit hoe ik Laravel Passport ...
try_prompt
generate_helper
disclaimerOnPageApi
tags
ai_answers
provider: openai
model: gpt-4.1-nano
Natuurlijk! Hier is een overzicht van hoe je een RESTful API ontwikkelt met Laravel die OAuth2 authenticatie gebruikt via Laravel Passport voor je boekbeheer onderwerp.
---
### 1. Laravel Passport installeren en configureren
**Stap 1: Passport installeren**
```bash
composer require laravel/passport
```
**Stap 2: Passport installeren en migraties uitvoeren**
```bash
php artisan migrate
php artisan passport:install
```
**Stap 3: Passport service provider registreren**
In `config/app.php` zou Laravel dit automatisch doen vanaf Laravel 7. Anders voeg toe:
```php
'providers' => [
// ...
Laravel\Passport\PassportServiceProvider::class,
],
```
**Stap 4: Passport in `AuthServiceProvider` registreren**
Open `app/Providers/AuthServiceProvider.php` en voeg binnen de `boot`-methode toe:
```php
use Laravel\Passport\Passport;
public function boot()
{
$this->registerPolicies();
Passport::routes();
}
```
**Stap 5: Authenticatie configureren**
In `config/auth.php`:
```php
'guards' => [
'api' => [
'driver' => 'passport',
'provider' => 'users',
],
],
```
**Stap 6: User model aanpassen**
In `app/Models/User.php` (of `app/User.php`):
```php
use Laravel\Passport\HasApiTokens;
class User extends Authenticatable
{
use HasApiTokens, Notifiable;
// ...
}
```
---
### 2. Client credentials beheer
**Client aanmaken**
Gebruik de CLI:
```bash
php artisan passport:client --client
```
Kies voor "Client Credentials" type. Dit geeft je een `client_id` en `client_secret`.
**Verwerven van een access token**
Voor server-to-server communicatie of app authenticatie:
```bash
curl -X POST http://your-laravel-app.com/oauth/token \
-H "Content-Type: application/x-www-form-urlencoded" \
-d "grant_type=client_credentials&client_id=YOUR_CLIENT_ID&client_secret=YOUR_CLIENT_SECRET&scope="
```
Dit geeft een access token dat je in de headers gebruikt.
---
### 3. Beveiligde endpoints definiëren met token validatie
**API routes instellen**
In `routes/api.php`:
```php
use App\Http\Controllers\BoekController;
Route::middleware('auth:api')->group(function () {
Route::get('/boeken', [BoekController::class, 'index']);
Route::post('/boeken', [BoekController::class, 'store']);
Route::get('/boeken/{id}', [BoekController::class, 'show']);
Route::put('/boeken/{id}', [BoekController::class, 'update']);
Route::delete('/boeken/{id}', [BoekController::class, 'destroy']);
});
```
**BoekController voorbeeld**
```php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Models\Boek;
class BoekController extends Controller
{
public function index()
{
return Boek::all();
}
// andere CRUD-methoden...
}
```
**Token validatie**
Door de middleware `'auth:api'` worden alle routes automatisch beveiligd en wordt een geldig access token vereist.
---
### 4. Voorbeeld API-aanroep met headers
**GET /boeken met Bearer token**
```bash
curl -H "Authorization: Bearer YOUR_ACCESS_TOKEN" \
http://your-laravel-app.com/api/boeken
```
**Verplichte headers**
- `Authorization: Bearer YOUR_ACCESS_TOKEN`
---
### Samenvatting
- Installeer Laravel Passport en voer `passport:install`.
- Registreer Passport routes en configureer de `auth.php` guard.
- Maak OAuth2 clients aan met `passport:client`.
- Vraag tokens aan via OAuth2 endpoints.
- Bescherm je routes met `'auth:api'` middleware.
- Verstuur API-verzoeken met de header `Authorization: Bearer <token>`.
---
Heeft u verdere vragen of hulp bij specifieke implementatie-details?
provider: deepseek
model: deepseek-chat
Zeker, ik help je met het ontwikkelen van een RESTful API voor boekbeheer met Laravel Passport. Hier is een complete handleiding:
## 1. Laravel Passport Installatie
```bash
# Installeer Passport via Composer
composer require laravel/passport
# Publiceer de migratiebestanden
php artisan vendor:publish --tag=passport-migrations
# Voer de migraties uit
php artisan migrate
# Publiceer de Passport configuratie
php artisan vendor:publish --tag=passport-config
# Genereer encryption keys
php artisan passport:install
```
## 2. Configuratie
Voeg in `app/Models/User.php`:
```php
use Laravel\Passport\HasApiTokens;
class User extends Authenticatable
{
use HasApiTokens, HasFactory, Notifiable;
}
```
In `config/auth.php`:
```php
'guards' => [
'api' => [
'driver' => 'passport',
'provider' => 'users',
],
],
```
## 3. Client Credentials Beheer
```bash
# Maak een nieuwe client aan
php artisan passport:client --client
# Bekijk bestaande clients
php artisan passport:client --list
# Verwijder een client
php artisan passport:client --revoke --client-id=1
```
## 4. Model en Migratie voor Boeken
```bash
php artisan make:model Book -m
```
In de migratiebestand:
```php
public function up()
{
Schema::create('books', function (Blueprint $table) {
$table->id();
$table->string('title');
$table->string('author');
$table->text('description');
$table->integer('publication_year');
$table->timestamps();
});
}
```
## 5. Beveiligde Endpoints
In `routes/api.php`:
```php
use App\Http\Controllers\BookController;
use Illuminate\Support\Facades\Route;
Route::post('/oauth/token', '\Laravel\Passport\Http\Controllers\AccessTokenController@issueToken');
Route::middleware('auth:api')->group(function () {
// Beveiligde routes
Route::apiResource('books', BookController::class);
Route::get('/user', function (Request $request) {
return $request->user();
});
});
// Onbeveiligde routes (optioneel)
Route::get('/public/books', [BookController::class, 'index']);
Route::get('/public/books/{id}', [BookController::class, 'show']);
```
## 6. BookController Voorbeeld
```php
<?php
namespace App\Http\Controllers;
use App\Models\Book;
use Illuminate\Http\Request;
use Illuminate\Http\JsonResponse;
class BookController extends Controller
{
public function index(): JsonResponse
{
$books = Book::all();
return response()->json($books);
}
public function store(Request $request): JsonResponse
{
$validated = $request->validate([
'title' => 'required|string|max:255',
'author' => 'required|string|max:255',
'description' => 'required|string',
'publication_year' => 'required|integer|min:1000|max:' . date('Y')
]);
$book = Book::create($validated);
return response()->json($book, 201);
}
public function show(Book $book): JsonResponse
{
return response()->json($book);
}
public function update(Request $request, Book $book): JsonResponse
{
$validated = $request->validate([
'title' => 'sometimes|string|max:255',
'author' => 'sometimes|string|max:255',
'description' => 'sometimes|string',
'publication_year' => 'sometimes|integer|min:1000|max:' . date('Y')
]);
$book->update($validated);
return response()->json($book);
}
public function destroy(Book $book): JsonResponse
{
$book->delete();
return response()->json(null, 204);
}
}
```
## 7. Authenticatie Headers Voorbeeld
**Token aanvragen:**
```bash
curl -X POST http://your-api.com/oauth/token \
-H "Accept: application/json" \
-H "Content-Type: application/json" \
-d '{
"grant_type": "password",
"client_id": "your-client-id",
"client_secret": "your-client-secret",
"username": "user@example.com",
"password": "password",
"scope": ""
}'
```
**Beveiligde endpoints benaderen:**
```bash
# Boeken ophalen
curl -X GET http://your-api.com/api/books \
-H "Accept: application/json" \
-H "Authorization: Bearer your-access-token"
# Nieuw boek toevoegen
curl -X POST http://your-api.com/api/books \
-H "Accept: application/json" \
-H "Content-Type: application/json" \
-H "Authorization: Bearer your-access-token" \
-d '{
"title": "De Avonden",
"author": "Gerard Reve",
"description": "Een klassieke Nederlandse roman",
"publication_year": 1947
}'
```
## 8. Extra Beveiliging
Voeg in je controller methods eventueel extra autorisatie toe:
```php
public function update(Request $request, Book $book)
{
// Controleer of gebruiker eigenaar is van het boek
if ($request->user()->id !== $book->user_id) {
return response()->json(['error' => 'Unauthorized'], 403);
}
// ... update logica
}
```
## 9. Environment Variabelen
In je `.env` bestand:
```env
PASSPORT_PRIVATE_KEY="-----BEGIN PRIVATE KEY-----\n..."
PASSPORT_PUBLIC_KEY="-----BEGIN PUBLIC KEY-----\n..."
```
Dit geeft je een complete basis voor een beveiligde boekbeheer API met OAuth2 authenticatie via Laravel Passport!