Security
Intermediate
4.8
20 min read
32.7K views

API Authentication & Security

Learn how to securely authenticate with CMzon WhatsApp Business API and implement best security practices to protect your application and customer data.

Security First

This guide covers essential security practices. Always follow these recommendations to protect your API and customer data.

Authentication Methods

CMzon supports multiple authentication methods to ensure secure access to your WhatsApp Business API. Choose the method that best fits your application's security requirements.

API Token Authentication (Recommended)

API tokens are the most secure and recommended method for authenticating with our API.

Example Request
curl -X POST "https://api.cmzon.com/v1/messages" \
  -H "Authorization: Bearer YOUR_API_TOKEN" \
  -H "Content-Type: application/json" \
  -d '{
    "to": "+1234567890",
    "type": "text",
    "text": {
      "body": "Hello from CMzon!"
    }
  }'
1

Generate API Token

In your CMzon dashboard, go to "API Settings" → "Generate New Token". Choose appropriate permissions for your use case.

2

Store Securely

Store your API token in environment variables or secure key management systems. Never hardcode tokens in your source code.

3

Include in Requests

Include the token in the Authorization header of all API requests:Authorization: Bearer YOUR_TOKEN

OAuth 2.0 Authentication

For applications that need more granular access control, OAuth 2.0 provides additional security features.

OAuth Flow Example
// Step 1: Get authorization code
GET https://api.cmzon.com/oauth/authorize?
  client_id=YOUR_CLIENT_ID&
  redirect_uri=YOUR_REDIRECT_URI&
  response_type=code&
  scope=whatsapp_business

// Step 2: Exchange code for token
POST https://api.cmzon.com/oauth/token
{
  "grant_type": "authorization_code",
  "client_id": "YOUR_CLIENT_ID",
  "client_secret": "YOUR_CLIENT_SECRET",
  "code": "AUTHORIZATION_CODE",
  "redirect_uri": "YOUR_REDIRECT_URI"
}

Benefits

  • • Granular permission control
  • • Token expiration management
  • • Revocable access tokens
  • • Audit trail capabilities

Use Cases

  • • Third-party integrations
  • • Multi-tenant applications
  • • User-specific access
  • • Enterprise deployments

Security Best Practices

Token Management

Critical Security Rules

  • • Never expose API tokens in client-side code
  • • Use environment variables for token storage
  • • Implement token rotation regularly
  • • Monitor token usage and revoke if compromised

Secure Storage

Environment Variables

Store tokens in environment variables, not in code

Key Management

Use AWS KMS, Azure Key Vault, or similar services

Encryption

Encrypt tokens at rest and in transit

Access Control

Principle of Least Privilege

Grant only necessary permissions

Token Expiration

Set appropriate expiration times

Regular Rotation

Rotate tokens periodically

Network Security

HTTPS Only

Always use HTTPS for API communications. Never send sensitive data over HTTP.

✅ https://api.cmzon.com/v1/messages

IP Whitelisting

Restrict API access to specific IP addresses for additional security.

Configure in dashboard settings
Add your server IPs only

Rate Limiting

Implement client-side rate limiting to prevent abuse and stay within API limits.

API Limits
  • • 80 messages per second
  • • 10,000 messages per day
  • • 1,000 messages per day (new accounts)
Best Practices
  • • Implement exponential backoff
  • • Monitor response headers
  • • Queue messages if needed

Error Handling & Monitoring

Proper error handling and monitoring are essential for maintaining security and reliability.

Common Authentication Errors

401 Unauthorized

Invalid or expired API token. Check your token and regenerate if necessary.

{ "error": { "code": 401, "message": "Invalid API token", "details": "Token has expired or is invalid" } }

403 Forbidden

Token doesn't have required permissions for this operation.

{ "error": { "code": 403, "message": "Insufficient permissions", "details": "Token lacks required scope for this operation" } }

429 Too Many Requests

Rate limit exceeded. Implement exponential backoff and retry logic.

{ "error": { "code": 429, "message": "Rate limit exceeded", "retry_after": 60 } }

Security Monitoring

Monitor for Suspicious Activity

  • • Unusual API usage patterns
  • • Failed authentication attempts
  • • Requests from unexpected IPs
  • • High error rates
  • • Unusual message volumes

Implement Alerts

  • • Set up monitoring dashboards
  • • Configure alert thresholds
  • • Log all API activities
  • • Regular security audits
  • • Incident response procedures

Implementation Examples

Node.js Example

Node.js Implementation
const axios = require('axios');

class CMzonAPI {
  constructor(apiToken) {
    this.apiToken = apiToken;
    this.baseURL = 'https://api.cmzon.com/v1';
  }

  async sendMessage(to, message) {
    try {
      const response = await axios.post(`${this.baseURL}/messages`, {
        to: to,
        type: 'text',
        text: {
          body: message
        }
      }, {
        headers: {
          'Authorization': `Bearer ${this.apiToken}`,
          'Content-Type': 'application/json'
        }
      });
      
      return response.data;
    } catch (error) {
      if (error.response?.status === 401) {
        throw new Error('Invalid API token');
      } else if (error.response?.status === 429) {
        throw new Error('Rate limit exceeded');
      }
      throw error;
    }
  }
}

// Usage
const api = new CMzonAPI(process.env.CMZON_API_TOKEN);
api.sendMessage('+1234567890', 'Hello from CMzon!')
  .then(result => console.log('Message sent:', result))
  .catch(error => console.error('Error:', error.message));

Python Example

Python Implementation
import requests
import os
from typing import Dict, Any

class CMzonAPI:
    def __init__(self, api_token: str):
        self.api_token = api_token
        self.base_url = 'https://api.cmzon.com/v1'
        self.headers = {
            'Authorization': f'Bearer {api_token}',
            'Content-Type': 'application/json'
        }
    
    def send_message(self, to: str, message: str) -> Dict[str, Any]:
        """Send a text message via WhatsApp Business API"""
        url = f'{self.base_url}/messages'
        data = {
            'to': to,
            'type': 'text',
            'text': {
                'body': message
            }
        }
        
        try:
            response = requests.post(url, json=data, headers=self.headers)
            response.raise_for_status()
            return response.json()
        except requests.exceptions.HTTPError as e:
            if e.response.status_code == 401:
                raise ValueError("Invalid API token")
            elif e.response.status_code == 429:
                raise ValueError("Rate limit exceeded")
            else:
                raise e

# Usage
api = CMzonAPI(os.getenv('CMZON_API_TOKEN'))
try:
    result = api.send_message('+1234567890', 'Hello from CMzon!')
    print(f"Message sent: {result}")
except ValueError as e:
    print(f"Error: {e}")

Security Questions?

Our security team is here to help you implement best practices and resolve any authentication issues.