Authentication overview
BuildPDF secures its API endpoints through a combination of API keys and HMAC (Hash-based Message Authentication Code) request signatures. These methods ensure that all requests originating from your application are verifiable and authorized, preventing unauthorized access to your BuildPDF account and its associated resources. Implementing secure authentication is a foundational step for integrating BuildPDF's PDF generation and manipulation API into your applications.
API keys provide a straightforward method for client identification, suitable for internal tools or applications where key exposure is minimal. For environments demanding higher security, such as public-facing applications or systems handling sensitive data, HMAC request signatures offer an additional layer of integrity and authenticity verification. This multi-layered approach allows developers to choose the appropriate security posture based on their application's specific requirements and risk profile.
Supported authentication methods
BuildPDF supports two primary authentication methods: API Keys and HMAC Request Signatures. Each method offers distinct advantages and is suited for different integration scenarios.
API Key
The API key is a unique, secret token assigned to your BuildPDF account. It is used to identify your application and authorize its requests to the BuildPDF API. When using API key authentication, your key must be included in the request headers of every API call. This method is simpler to implement and is often preferred for server-side applications where keys can be securely stored and managed.
Implementation details:
- Header Name:
X-BuildPDF-API-Key - Header Value: Your unique API key
- Example:
X-BuildPDF-API-Key: sk_live_your_api_key_here
Using an API key is a common practice for identifying a calling application or user without requiring a full login flow. For example, Stripe's API authentication also relies on API keys for securing requests.
HMAC Request Signature
HMAC request signatures provide a cryptographic mechanism to verify both the authenticity and integrity of a request. This method involves generating a unique signature for each API request using a secret key and a hashing algorithm. The signature is then included in the request headers, allowing BuildPDF to verify that the request has not been tampered with and originated from a legitimate source. This method is particularly useful for webhooks and public-facing APIs where request origin and integrity are critical, similar to how Twilio secures webhooks.
Implementation details:
- Algorithm: HMAC-SHA256
- Signed components: Request body, timestamp, HTTP method, request path.
- Header Name:
X-BuildPDF-SignatureandX-BuildPDF-Timestamp - Signature generation process:
- Concatenate the HTTP method (e.g.,
POST), request path (e.g.,/v1/documents), current timestamp (Unix epoch seconds), and the raw request body. - Hash this concatenated string using HMAC-SHA256 with your BuildPDF secret API key as the key.
- Encode the resulting hash in hexadecimal format.
- Include the timestamp in the
X-BuildPDF-Timestampheader and the hexadecimal signature in theX-BuildPDF-Signatureheader.
- Concatenate the HTTP method (e.g.,
This method prevents replay attacks and ensures that the request payload has not been modified in transit.
Authentication Methods Comparison
| Method | When to Use | Security Level |
|---|---|---|
| API Key | Server-side applications, internal tools, rapid prototyping | Moderate (relies on secure key storage) |
| HMAC Request Signature | Public-facing APIs, webhooks, high-security applications, integrity verification | High (verifies authenticity and integrity) |
Getting your credentials
To access the BuildPDF API, you will need to obtain your API key and secret from your BuildPDF account dashboard. Follow these steps:
- Sign Up/Log In: Navigate to the BuildPDF website and either create a new account or log in to your existing one.
- Access Dashboard: Once logged in, go to your account dashboard.
- Navigate to API Settings: Look for a section labeled "API Keys," "Developer Settings," or similar. This is typically found in the settings or profile management area.
- Generate Keys: You will find options to generate new API keys or view existing ones. BuildPDF provides both a publishable key (if applicable for client-side use, though typically not for PDF generation) and a secret key. For server-to-server authentication, use the secret key.
- Securely Store Keys: Copy your API key and secret. It is critical to store these credentials securely, ideally in environment variables or a secrets management service, and avoid hardcoding them directly into your application code.
BuildPDF offers a free tier that includes 50 documents per month, allowing you to generate and test credentials without an immediate financial commitment. This is an ideal way to familiarize yourself with the authentication process and API capabilities.
Authenticated request example
Below are examples demonstrating how to make an authenticated request using both API Key and HMAC signature methods, primarily focusing on the Node.js SDK, as it is a primary language example for BuildPDF.
API Key Authentication (Node.js)
This example shows how to include your API key in the X-BuildPDF-API-Key header when making a request to generate a PDF.
const axios = require('axios');
const BUILD_PDF_API_KEY = process.env.BUILD_PDF_API_KEY; // Stored securely
async function generatePdfWithApiKey() {
try {
const response = await axios.post('https://api.buildpdf.com/v1/documents/generate', {
html: '<h1>Hello World!</h1><p>This is a test PDF.</p>',
options: {
format: 'A4'
}
}, {
headers: {
'X-BuildPDF-API-Key': BUILD_PDF_API_KEY,
'Content-Type': 'application/json'
},
responseType: 'arraybuffer' // For binary PDF data
});
// Save the PDF buffer to a file
// fs.writeFileSync('output.pdf', response.data);
console.log('PDF generated successfully with API Key.');
} catch (error) {
console.error('Error generating PDF with API Key:', error.response ? error.response.data : error.message);
}
}
generatePdfWithApiKey();
HMAC Request Signature Authentication (Node.js)
This more complex example demonstrates how to generate and include the HMAC signature in your request. Replace YOUR_API_SECRET with your actual BuildPDF API secret.
const axios = require('axios');
const crypto = require('crypto');
const BUILD_PDF_API_KEY = process.env.BUILD_PDF_API_KEY;
const BUILD_PDF_API_SECRET = process.env.BUILD_PDF_API_SECRET; // Your HMAC secret
async function generatePdfWithHmacSignature() {
const requestBody = {
html: '<h1>Signed Document</h1><p>This PDF request is secured with HMAC.</p>',
options: {
format: 'Letter'
}
};
const requestBodyString = JSON.stringify(requestBody);
const timestamp = Math.floor(Date.now() / 1000); // Unix epoch seconds
const method = 'POST';
const path = '/v1/documents/generate';
const stringToSign = `${method}\n${path}\n${timestamp}\n${requestBodyString}`;
const hmac = crypto.createHmac('sha256', BUILD_PDF_API_SECRET);
hmac.update(stringToSign);
const signature = hmac.digest('hex');
try {
const response = await axios.post(`https://api.buildpdf.com${path}`, requestBody,
{
headers: {
'X-BuildPDF-API-Key': BUILD_PDF_API_KEY,
'X-BuildPDF-Timestamp': timestamp.toString(),
'X-BuildPDF-Signature': signature,
'Content-Type': 'application/json'
},
responseType: 'arraybuffer'
}
);
// fs.writeFileSync('signed_output.pdf', response.data);
console.log('PDF generated successfully with HMAC Signature.');
} catch (error) {
console.error('Error generating PDF with HMAC Signature:', error.response ? error.response.data : error.message);
}
}
generatePdfWithHmacSignature();
For other SDKs like Python, Ruby, PHP, and Go, similar logic applies for constructing the request and headers. Refer to the BuildPDF developer documentation for language-specific examples.
Security best practices
Adhering to security best practices when authenticating with BuildPDF is crucial for protecting your data and preventing unauthorized access.
- Keep API Keys and Secrets Confidential: Treat your API keys and secrets as sensitive credentials. Never expose them in client-side code, public repositories, or unsecured environments. Store them in environment variables, a secrets management service (e.g., AWS Secrets Manager, Google Secret Manager), or a secure configuration file.
- Use HTTPS/TLS: All communication with the BuildPDF API must occur over HTTPS (TLS 1.2 or higher). This encrypts data in transit, protecting your API key, request payloads, and generated PDF data from eavesdropping. BuildPDF enforces HTTPS for all API endpoints.
- Rotate API Keys Regularly: Periodically rotate your API keys and secrets. This practice limits the window of exposure if a key is compromised. BuildPDF's dashboard provides functionality for key rotation.
- Implement Least Privilege: If BuildPDF introduces fine-grained access control in the future, configure API keys with the minimum necessary permissions required for your application's functionality. Avoid using keys with broad administrative access for routine operations.
- Monitor API Usage: Regularly review your BuildPDF API usage logs for any unusual activity or unexpected spikes in requests, which could indicate a compromised key or malicious activity.
- Validate Webhook Signatures: If you are using BuildPDF webhooks, always verify the HMAC signature included in the webhook payload. This ensures that the webhook event truly originated from BuildPDF and has not been tampered with. This is a standard security measure for secure cloud integrations.
- Error Handling and Logging: Implement robust error handling for authentication failures. Log these events securely for auditing and to detect potential attack attempts, but avoid logging the actual API keys or secrets.
- Client-Side Concerns: Avoid directly embedding BuildPDF API keys in client-side applications (e.g., JavaScript in a browser). If client-side PDF generation is required, route requests through a secure backend proxy that can add the necessary authentication headers.