header('Authorization', ''); if (! str_starts_with($header, 'Bearer ')) { return $this->unauthorizedResponse('missing_bearer'); } $token = substr($header, 7); $userId = Cache::get('api_token:'.$token); if (! $userId) { return $this->unauthorizedResponse('token_unknown'); } $user = User::find($userId); if (! $user) { return $this->unauthorizedResponse('user_missing'); } Auth::login($user); // for policies if needed return $next($request); } private function unauthorizedResponse(string $reason): JsonResponse { return ApiError::response( 'unauthorized', 'Unauthorized', 'Authentication is required to access this resource.', Response::HTTP_UNAUTHORIZED, ['reason' => $reason] ); } }