Dokumentation

Authentication & Security

Learn how to securely authenticate with K-OTP API and implement best security practices.

API Key Authentication

K-OTP uses API keys for authentication. All requests must include your API key in the Authorization header.

Generating API Keys

  1. Log in to your K-OTP dashboard
  2. Navigate to Settings > API Keys
  3. Click "Generate New Key"
  4. Give your key a descriptive name
  5. Configure security settings
  6. Copy and securely store the key

Using API Keys

Include your API key in every request:

curl -X POST "https://api.k-otp.dev/v1/send" \
  -H "Authorization: Bearer YOUR_API_KEY" \
  -H "Content-Type: application/json"

Key Types

TypeDescriptionUse Case
ProductionFull access to production APILive applications
SandboxAccess to test environmentDevelopment and testing
Read-onlyLimited to GET requestsAnalytics and monitoring

Security Best Practices

1. Secure Key Storage

// ✅ Good: Use environment variables
const apiKey = process.env.K_OTP_API_KEY;

// ❌ Bad: Hardcode in source code
const apiKey = "kotp_live_1234567890abcdef";

2. Key Rotation

  • Rotate API keys every 90 days
  • Use multiple keys for different environments
  • Implement graceful key transitions
// Example: Key rotation implementation
const primaryKey = process.env.K_OTP_PRIMARY_KEY;
const fallbackKey = process.env.K_OTP_FALLBACK_KEY;

async function apiRequest(endpoint, data) {
  try {
    return await makeRequest(endpoint, data, primaryKey);
  } catch (error) {
    if (error.status === 401) {
      return await makeRequest(endpoint, data, fallbackKey);
    }
    throw error;
  }
}

3. IP Allowlisting

Restrict API key usage to specific IP addresses:

  1. Go to API Keys in your dashboard
  2. Click "Edit" on your key
  3. Add allowed IP addresses or CIDR blocks
  4. Save changes
# Example IP allowlist
192.168.1.0/24
203.0.113.0/24
2001:db8::/32

4. Domain Restrictions

For client-side usage, restrict to specific domains:

// This key only works from allowed domains
const clientKey = "kotp_client_1234567890abcdef";

Authentication Patterns

Server-to-Server

Use your private API key directly:

import requests

headers = {
    'Authorization': 'Bearer kotp_live_1234567890abcdef',
    'Content-Type': 'application/json'
}

response = requests.post(
    'https://api.k-otp.dev/v1/send',
    headers=headers,
    json={
        'to': '+1234567890',
        'method': 'sms',
        'type': 'verification'
    }
)

Client-Side with Proxy

Never expose private keys in client-side code. Use a proxy:

// Client-side: Call your backend
const response = await fetch('/api/send-otp', {
  method: 'POST',
  headers: { 'Content-Type': 'application/json' },
  body: JSON.stringify({ phone: '+1234567890' })
});

// Your backend: Use private key
app.post('/api/send-otp', async (req, res) => {
  const response = await fetch('https://api.k-otp.dev/v1/send', {
    method: 'POST',
    headers: {
      'Authorization': `Bearer ${process.env.K_OTP_API_KEY}`,
      'Content-Type': 'application/json'
    },
    body: JSON.stringify({
      to: req.body.phone,
      method: 'sms',
      type: 'verification'
    })
  });
  
  const result = await response.json();
  res.json(result);
});

Rate Limiting

K-OTP implements multiple rate limiting layers:

Per-Key Limits

  • 1,000 requests/minute per API key
  • 10 OTP sends/minute per recipient
  • 5 verification attempts per OTP

Headers

Rate limit information is included in response headers:

X-RateLimit-Limit: 1000
X-RateLimit-Remaining: 999
X-RateLimit-Reset: 1642248600
X-RateLimit-Window: 60

Handling Rate Limits

async function sendOTP(data) {
  const response = await fetch('https://api.k-otp.dev/v1/send', {
    method: 'POST',
    headers: {
      'Authorization': `Bearer ${apiKey}`,
      'Content-Type': 'application/json'
    },
    body: JSON.stringify(data)
  });

  if (response.status === 429) {
    const resetTime = response.headers.get('X-RateLimit-Reset');
    const waitTime = (resetTime * 1000) - Date.now();
    
    throw new Error(`Rate limited. Retry after ${waitTime}ms`);
  }

  return response.json();
}

Webhook Security

Secure your webhook endpoints to ensure requests come from K-OTP:

Signature Verification

const crypto = require('crypto');

function verifyWebhookSignature(payload, signature, secret) {
  const expectedSignature = crypto
    .createHmac('sha256', secret)
    .update(payload)
    .digest('hex');
    
  return crypto.timingSafeEqual(
    Buffer.from(signature, 'hex'),
    Buffer.from(expectedSignature, 'hex')
  );
}

app.post('/webhook', express.raw({type: 'application/json'}), (req, res) => {
  const signature = req.headers['x-kotp-signature'];
  const isValid = verifyWebhookSignature(
    req.body,
    signature,
    process.env.WEBHOOK_SECRET
  );
  
  if (!isValid) {
    return res.status(401).send('Unauthorized');
  }
  
  // Process webhook
  res.status(200).send('OK');
});

GDPR Compliance

K-OTP is GDPR compliant and provides tools for data protection:

Data Retention

  • OTP records are automatically deleted after 30 days
  • Configure custom retention periods
  • Export data for compliance reports

User Rights

  • Right to Access: Export user's OTP history
  • Right to Deletion: Remove user data on request
  • Right to Portability: Data export in JSON format
// Delete user data
await fetch('https://api.k-otp.dev/v1/users/user_123/delete', {
  method: 'DELETE',
  headers: {
    'Authorization': `Bearer ${apiKey}`
  }
});

// Export user data
const userData = await fetch('https://api.k-otp.dev/v1/users/user_123/export', {
  headers: {
    'Authorization': `Bearer ${apiKey}`
  }
});

Security Monitoring

Monitor your API usage for security threats:

Audit Logs

All API calls are logged with:

  • Timestamp and IP address
  • API key used
  • Request details (sanitized)
  • Response status

Alerts

Set up alerts for:

  • Unusual API usage patterns
  • Failed authentication attempts
  • Rate limit violations
  • Suspicious IP addresses

Security Dashboard

Access real-time security metrics:

  • API key usage statistics
  • Geographic request distribution
  • Error rate monitoring
  • Threat detection alerts

Multi-Factor Authentication

Secure your K-OTP account with MFA:

  1. Go to Account Settings > Security
  2. Click "Enable Two-Factor Authentication"
  3. Scan QR code with authenticator app
  4. Enter verification code
  5. Save backup codes securely

Emergency Procedures

Compromised API Key

If you suspect a key is compromised:

  1. Immediately revoke the key in dashboard
  2. Generate a new key with different permissions
  3. Update your applications with new key
  4. Monitor logs for unauthorized usage
  5. Report incident to K-OTP security team

Account Lockout

If your account is locked:

  1. Check email for security notifications
  2. Contact support with verification details
  3. Provide proof of identity
  4. Follow account recovery process

Compliance Certifications

K-OTP maintains the following certifications:

  • SOC 2 Type II: Annual compliance audit
  • ISO 27001: Information security management
  • PCI DSS: Payment card industry compliance
  • GDPR: European data protection regulation
  • HIPAA: Healthcare data protection (available)