Authentication overview

Hookdeck employs distinct authentication mechanisms for its API and for the webhooks it sends to user endpoints. For interacting with the Hookdeck API to manage resources such as sources, destinations, and connections, API keys are the primary method of authentication. These keys grant programmatic access to your Hookdeck account and its configurations.

Conversely, when Hookdeck delivers webhooks to your application, it uses webhook signatures to allow your receiving endpoint to verify the authenticity and integrity of the incoming payload. This ensures that the webhook originated from Hookdeck and has not been tampered with during transit. Implementing signature verification is a critical security measure for any system consuming webhooks.

The combination of API key authentication for API requests and webhook signature verification for incoming webhooks establishes a secure framework for managing and processing event-driven data through the Hookdeck platform. Developers are advised to implement both aspects diligently to maintain a secure integration.

Supported authentication methods

Hookdeck supports two primary authentication methods tailored to different interaction types:

  1. API Keys: Used for authenticating requests made to the Hookdeck API. These keys are typically passed in the Authorization header of HTTP requests.
  2. Webhook Signatures: Used by Hookdeck to sign outgoing webhook payloads, allowing your application to verify the sender and integrity of the data.

The table below summarizes the authentication methods, their typical use cases, and associated security considerations:

Method When to Use Security Level Details
API Keys Programmatic access to Hookdeck API (e.g., creating sources, managing destinations). High (if managed securely) Bearer token in Authorization header. Must be kept confidential.
Webhook Signatures Verifying incoming webhooks sent by Hookdeck to your endpoint. High (if implemented correctly) HMAC-SHA256 signature in Hookdeck-Signature header. Requires secret key for verification.

API keys are a common method for authenticating API requests, often used in conjunction with HTTPS to protect credentials in transit. For example, Stripe's API authentication also relies on API keys passed in the Authorization header. Webhook signatures, on the other hand, provide an additional layer of security beyond HTTPS by allowing the recipient to cryptographically verify the sender's identity and message integrity, a practice also followed by services like Twilio's webhook security guide.

Getting your credentials

To obtain the necessary credentials for authenticating with Hookdeck, you will primarily use the Hookdeck Dashboard.

API Keys

  1. Access the Dashboard: Log in to your Hookdeck Dashboard.
  2. Navigate to API Keys: Go to the "Settings" section, then select "API Keys".
  3. Generate a New Key: You can generate new API keys as needed. It is recommended to create separate keys for different applications or environments (e.g., development, staging, production) to facilitate key rotation and access management.
  4. Store Securely: Once generated, API keys are typically displayed only once. Copy your key and store it in a secure location, such as an environment variable or a secrets manager. Avoid hardcoding API keys directly into your source code.

Hookdeck API keys are typically prefixed (e.g., hk_) to help identify them and distinguish between different types of keys if applicable. For detailed instructions on managing API keys, refer to the Hookdeck API Keys documentation.

Webhook Signing Secrets

Each Hookdeck source or connection that sends webhooks will have an associated signing secret. This secret is crucial for verifying the authenticity of incoming webhooks.

  1. Select a Source or Connection: In the Hookdeck Dashboard, navigate to the specific source or connection for which you want to retrieve the webhook signing secret.
  2. Locate the Secret: Within the settings or details page for that source/connection, you will find the "Signing Secret" or "Webhook Secret".
  3. Copy and Configure: Copy this secret. You will use it in your webhook receiving endpoint to compute and compare the signature of incoming payloads. This secret must also be stored securely and not exposed publicly.

For a comprehensive guide on setting up and verifying webhook signatures, consult the Hookdeck Webhook Signatures documentation.

Authenticated request example

This example demonstrates how to make an authenticated request to the Hookdeck API using an API key in Node.js, and how to verify an incoming webhook signature.

API Request with API Key (Node.js)

To interact with the Hookdeck API, include your API key in the Authorization header as a Bearer token.

const axios = require('axios');

const HOOKDECK_API_KEY = process.env.HOOKDECK_API_KEY; // Stored securely as an environment variable
const API_BASE_URL = 'https://api.hookdeck.com/2023-01-01';

async function createSource() {
  try {
    const response = await axios.post(
      `${API_BASE_URL}/sources`,
      {
        name: 'My New Source',
        description: 'Source for example application'
      },
      {
        headers: {
          'Authorization': `Bearer ${HOOKDECK_API_KEY}`,
          'Content-Type': 'application/json'
        }
      }
    );
    console.log('Source created:', response.data);
    return response.data;
  } catch (error) {
    console.error('Error creating source:', error.response ? error.response.data : error.message);
    throw error;
  }
}

createSource();

Webhook Signature Verification (Node.js)

When receiving webhooks from Hookdeck, you must verify the signature to ensure the request's authenticity. Hookdeck provides SDKs that simplify this process, such as the Hookdeck Node.js SDK for webhook verification.

const express = require('express');
const crypto = require('crypto');
const bodyParser = require('body-parser');

const app = express();
const PORT = process.env.PORT || 3000;

// Get your webhook signing secret from the Hookdeck Dashboard
const HOOKDECK_WEBHOOK_SECRET = process.env.HOOKDECK_WEBHOOK_SECRET; 

// Raw body is required for signature verification
app.use(bodyParser.json({ 
  verify: (req, res, buf) => {
    req.rawBody = buf;
  }
}));

app.post('/webhook', (req, res) => {
  const signature = req.headers['hookdeck-signature'];
  const payload = req.rawBody.toString();

  if (!signature) {
    return res.status(400).send('Webhook signature missing');
  }

  try {
    const [timestamp, signatureHash] = signature.split(',').map(part => part.split('=')[1]);
    
    // Construct the signed payload string
    const signedPayload = `${timestamp}.${payload}`;

    // Compute the expected signature
    const expectedSignature = crypto
      .createHmac('sha256', HOOKDECK_WEBHOOK_SECRET)
      .update(signedPayload)
      .digest('hex');

    if (signatureHash !== expectedSignature) {
      console.warn('Invalid webhook signature detected.');
      return res.status(401).send('Invalid signature');
    }

    // Optional: Check timestamp to prevent replay attacks
    const tolerance = 300; // 5 minutes
    const now = Math.floor(Date.now() / 1000);
    if (parseInt(timestamp) < (now - tolerance)) {
      console.warn('Webhook received outside of timestamp tolerance.');
      return res.status(400).send('Stale webhook');
    }

    console.log('Webhook body:', req.body);
    // Process the webhook event
    res.status(200).send('Webhook received and verified');

  } catch (error) {
    console.error('Error verifying webhook signature:', error.message);
    res.status(500).send('Error processing webhook');
  }
});

app.listen(PORT, () => {
  console.log(`Server listening on port ${PORT}`);
});

This example manually computes the signature. For production environments, utilizing Hookdeck's official SDKs or libraries is generally recommended as they often handle edge cases and nuances of signature verification more robustly.

Security best practices

Implementing strong authentication and security practices is essential when integrating with Hookdeck. Adhering to these best practices helps protect your data and maintain the integrity of your systems.

  • Keep API Keys Confidential: Never expose your Hookdeck API keys in client-side code, public repositories, or unsecured environments. Store them as environment variables or use a dedicated secrets management service.
  • Rotate API Keys Regularly: Periodically rotate your API keys. This practice minimizes the window of exposure if a key is compromised. Remove old keys from your Hookdeck Dashboard after updating your applications.
  • Use Least Privilege: If Hookdeck introduces granular API key permissions, grant API keys only the minimum necessary permissions required for their intended function.
  • Implement Webhook Signature Verification: Always verify webhook signatures for every incoming webhook from Hookdeck. This confirms that the webhook originated from Hookdeck and that its payload has not been altered.
  • Protect Webhook Signing Secrets: Treat webhook signing secrets with the same level of confidentiality as API keys. They should never be hardcoded or exposed publicly.
  • Validate Webhook Timestamps: Include timestamp validation as part of your webhook signature verification process to mitigate replay attacks. Hookdeck's signature includes a timestamp that you can compare against the current time within a reasonable tolerance.
  • Use HTTPS for all Endpoints: Ensure that all your webhook receiving endpoints are secured with HTTPS. This encrypts data in transit, protecting against eavesdropping and man-in-the-middle attacks.
  • Monitor for Anomalies: Regularly monitor your Hookdeck activity logs and your application's logs for any unusual authentication attempts or webhook delivery patterns that could indicate a security incident.
  • Review Access Controls: Periodically review who has access to your Hookdeck Dashboard and API keys. Remove access for individuals who no longer require it.
  • Utilize Hookdeck's Security Features: Leverage other security features offered by Hookdeck, such as IP allowlisting for inbound webhooks, if available, to further restrict access to your endpoints.

By consistently applying these security best practices, you can significantly enhance the security posture of your Hookdeck integration and protect your data from potential vulnerabilities.