You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在接收端检查CURL请求API Key授权及验证Token匹配(无数据库)

Hey there! Let's get your API Key validation set up properly for your cross-site curl data push. I'll break this down into clear, actionable steps based on your current code:

1. Tweak the Sender Code: Move API Key to Request Headers (More Secure)

Right now you're passing the API Key as a parameter, but putting it in request headers is a better practice—it avoids exposing the key in URL logs or browser history. Here's how to adjust your curl code:

$payload = json_encode(array("users" => $json['users']));
$apikey = 'OTM2NTQ0MwMTA3MDYxMQND...';

// Initialize curl with your receiver URL
$ch = curl_init('https://your-receiver-domain.com/endpoint');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $payload);

// Add API Key to request headers (we'll use a custom X-API-Key header here)
curl_setopt($ch, CURLOPT_HTTPHEADER, [
    'Content-Type: application/json',
    "X-API-Key: {$apikey}"
]);

// Execute and close the request
$response = curl_exec($ch);
curl_close($ch);
2. Receiver Code: Validate the API Key (No Database Needed)

Since you don't want to pull the key from a database, we'll hardcode a valid key directly (but use environment variables for production to avoid leaking it in code repositories). Here's a PHP receiver example:

// Define your valid API Key (use getenv('VALID_API_KEY') in production to pull from server environment)
$VALID_API_KEY = 'OTM2NTQ0MwMTA3MDYxMQND...';

// Grab the API Key from the incoming request headers
$requestApiKey = $_SERVER['HTTP_X_API_KEY'] ?? '';

// First, validate the API Key
if ($requestApiKey !== $VALID_API_KEY) {
    http_response_code(401); // Send "Unauthorized" status code
    echo json_encode(['error' => 'Invalid or missing API Key']);
    exit; // Stop execution if validation fails
}

// If validation passes, process the incoming payload
$rawPayload = file_get_contents('php://input');
$payload = json_decode($rawPayload, true);

if ($payload && isset($payload['users'])) {
    // Add your business logic here (e.g., save users to database, process data)
    http_response_code(200);
    echo json_encode(['status' => 'success', 'message' => 'Data received and processed']);
} else {
    http_response_code(400); // Send "Bad Request" if payload is invalid
    echo json_encode(['error' => 'Invalid or missing payload data']);
}
3. How to Check if the API Key is Authorized

The validation step above is the core of checking authorization, but here are extra tips to harden this process:

  • Use Standard Status Codes: Return 401 Unauthorized for invalid keys and 403 Forbidden if you want to block specific IPs (see below)
  • Restrict by IP (Optional): Add an extra layer of security by only allowing requests from your sender server's IP:
    $ALLOWED_IPS = ['123.45.67.89', 'your-sender-server-public-ip'];
    $clientIp = $_SERVER['REMOTE_ADDR'];
    if (!in_array($clientIp, $ALLOWED_IPS)) {
        http_response_code(403);
        echo json_encode(['error' => 'Forbidden: Unauthorized IP']);
        exit;
    }
    
  • Generate Strong API Keys: Use a cryptographically secure random generator like openssl rand -hex 32 to create long, unguessable keys
  • Log Failed Attempts: Keep a log of invalid key attempts (IP, timestamp, error type) to detect potential attacks

内容的提问来源于stack exchange,提问作者chintuu raj

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.22 09:09:16