From acaa791eda09e1fa26e3930e2281fe7cf46dfd36 Mon Sep 17 00:00:00 2001 From: Ovidiu U Date: Fri, 10 Apr 2026 17:56:14 +0100 Subject: [PATCH] feat: allow Sanctum-authenticated sessions through VerifyApiKey middleware Enables stateful API via Sanctum so the Vue SPA can call /api/* routes using cookie auth, without requiring an X-Api-Key header. Co-Authored-By: Claude Sonnet 4.6 --- app/Http/Middleware/VerifyApiKey.php | 7 ++++- bootstrap/app.php | 2 +- tests/Feature/VerifyApiKeyMiddlewareTest.php | 29 ++++++++++++++++++++ 3 files changed, 36 insertions(+), 2 deletions(-) create mode 100644 tests/Feature/VerifyApiKeyMiddlewareTest.php diff --git a/app/Http/Middleware/VerifyApiKey.php b/app/Http/Middleware/VerifyApiKey.php index 3f01076..115c606 100644 --- a/app/Http/Middleware/VerifyApiKey.php +++ b/app/Http/Middleware/VerifyApiKey.php @@ -4,9 +4,10 @@ namespace App\Http\Middleware; use Closure; use Illuminate\Http\Request; +use Illuminate\Support\Facades\Auth; use Symfony\Component\HttpFoundation\Response; -class VerifyApiKey +final class VerifyApiKey { /** * Handle an incoming request. @@ -15,6 +16,10 @@ class VerifyApiKey */ public function handle(Request $request, Closure $next): Response { + if (Auth::guard('sanctum')->check()) { + return $next($request); + } + if ($request->header('X-Api-Key') !== config('app.api_secret_key')) { abort(403); } diff --git a/bootstrap/app.php b/bootstrap/app.php index 6086def..c79ed7f 100644 --- a/bootstrap/app.php +++ b/bootstrap/app.php @@ -13,7 +13,7 @@ return Application::configure(basePath: dirname(__DIR__)) health: '/up', ) ->withMiddleware(function (Middleware $middleware): void { - // + $middleware->statefulApi(); }) ->withExceptions(function (Exceptions $exceptions): void { $exceptions->shouldRenderJsonWhen(fn (Request $request) => $request->is('api/*')); diff --git a/tests/Feature/VerifyApiKeyMiddlewareTest.php b/tests/Feature/VerifyApiKeyMiddlewareTest.php new file mode 100644 index 0000000..fa1dcfa --- /dev/null +++ b/tests/Feature/VerifyApiKeyMiddlewareTest.php @@ -0,0 +1,29 @@ +getJson('/api/stations?postcode=SW1A1AA&fuel_type=petrol'); + + $response->assertStatus(403); +}); + +it('accepts requests with valid api key', function (): void { + config(['app.api_secret_key' => 'test-secret']); + + $response = $this->withHeader('X-Api-Key', 'test-secret') + ->getJson('/api/stations?postcode=SW1A1AA&fuel_type=petrol'); + + // 403 would mean middleware rejected — any other status means it passed through + expect($response->status())->not->toBe(403); +}); + +it('accepts requests from sanctum authenticated users', function (): void { + $user = User::factory()->create(); + Sanctum::actingAs($user); + + $response = $this->getJson('/api/stations?postcode=SW1A1AA&fuel_type=petrol'); + + expect($response->status())->not->toBe(403); +});