Skip to content

Authentication

The 0.link API uses API key-based authentication for secure access to your resources. This guide covers authentication methods, security best practices, and troubleshooting.

API Key Authentication

Bearer Token Format

Include your API key in the Authorization header using the Bearer token format:

bash
Authorization: Bearer 0link_sk_your_api_key_here

Complete Example

bash
curl -X GET \
  -H "Authorization: Bearer 0link_sk_1234567890abcdef1234567890abcdef" \
  -H "Content-Type: application/json" \
  https://api.0link.com/v2/account

Authentication Methods

Always include the API key in the Authorization header:

javascript
// JavaScript fetch
const response = await fetch('https://api.0link.com/v2/projects', {
  headers: {
    'Authorization': 'Bearer 0link_sk_your_api_key_here',
    'Content-Type': 'application/json'
  }
});
python
# Python requests
import requests

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

response = requests.get('https://api.0link.com/v2/projects', headers=headers)

Deprecated

Using API keys in query parameters is deprecated and less secure. Use the Authorization header instead.

bash
# Deprecated - do not use
curl https://api.0link.com/v2/projects?api_key=your_key_here

API Key Types

Secret Keys (sk_)

Primary authentication method for server-side applications:

0link_sk_1234567890abcdef1234567890abcdef

Characteristics:

  • ✅ Full API access based on permissions
  • ✅ Server-side use only
  • ✅ No CORS restrictions
  • ❌ Never expose in client-side code

Public Keys (pk_) - Coming Soon

For client-side applications with limited scope:

0link_pk_1234567890abcdef1234567890abcdef

Characteristics:

  • ✅ Limited read-only access
  • ✅ Safe for client-side use
  • ✅ CORS-enabled endpoints
  • ❌ Cannot modify resources

Authentication Flow

1. API Key Validation

Every request validates your API key:

mermaid
graph LR
    A[Client Request] --> B{Valid API Key?}
    B -->|Yes| C{Has Permissions?}
    B -->|No| D[401 Unauthorized]
    C -->|Yes| E[Process Request]
    C -->|No| F[403 Forbidden]

2. Permission Check

After authentication, the API checks if your key has the required permissions:

json
{
  "endpoint": "POST /projects",
  "required_permission": "write",
  "api_key_permissions": ["read", "write"],
  "result": "allowed"
}

3. Request Processing

Valid, authorized requests are processed and return data:

json
{
  "status": "success",
  "data": {
    "id": "proj_123",
    "name": "New Project"
  }
}

Security Best Practices

Key Storage

Environment Variables ✅

bash
# .env file
ZEROLINK_API_KEY=0link_sk_your_api_key_here
javascript
const apiKey = process.env.ZEROLINK_API_KEY;
if (!apiKey) {
  throw new Error('API key not configured');
}

Configuration Files ❌

javascript
// DON'T DO THIS
const config = {
  apiKey: '0link_sk_1234567890abcdef1234567890abcdef' // Never hardcode
};

Version Control ❌

bash
# DON'T DO THIS
git add .env
git commit -m "Add API key" # Never commit keys

Key Rotation

Regularly rotate your API keys:

mermaid
graph TD
    A[Generate New Key] --> B[Update Applications]
    B --> C[Test in Staging]
    C --> D[Deploy to Production]
    D --> E[Verify New Key Works]
    E --> F[Delete Old Key]

Access Control

Use the principle of least privilege:

json
{
  "development_key": {
    "permissions": ["read", "write"],
    "environment": "development"
  },
  "production_key": {
    "permissions": ["read"],
    "environment": "production"
  },
  "admin_key": {
    "permissions": ["read", "write", "delete", "admin"],
    "environment": "production",
    "note": "Use sparingly"
  }
}

Error Handling

401 Unauthorized

Cause: Missing or invalid API key

json
{
  "status": "error",
  "error": {
    "code": "UNAUTHORIZED",
    "message": "Authentication required",
    "details": "No valid API key provided"
  }
}

Common Causes:

  • Missing Authorization header
  • Malformed API key format
  • Deleted or expired API key
  • Incorrect Bearer token format

Solutions:

bash
# Check header format
curl -H "Authorization: Bearer 0link_sk_..." # ✅ Correct
curl -H "Authorization: 0link_sk_..." # ❌ Missing "Bearer"
curl -H "Api-Key: 0link_sk_..." # ❌ Wrong header name

403 Forbidden

Cause: Valid key but insufficient permissions

json
{
  "status": "error",
  "error": {
    "code": "INSUFFICIENT_PERMISSIONS",
    "message": "Access denied",
    "required_permission": "write",
    "current_permissions": ["read"]
  }
}

Solutions:

  • Update API key permissions in dashboard
  • Use a different key with appropriate permissions
  • Contact support for permission issues

429 Rate Limited

Cause: Too many requests

json
{
  "status": "error",
  "error": {
    "code": "RATE_LIMIT_EXCEEDED",
    "message": "Too many requests",
    "retry_after": 60
  }
}

Solutions:

  • Implement exponential backoff
  • Reduce request frequency
  • Upgrade to a higher plan
  • Use multiple API keys if needed

Testing Authentication

Verify API Key

Test your API key with the ping endpoint:

bash
curl -H "Authorization: Bearer YOUR_API_KEY" \
     https://api.0link.com/v2/ping

Expected response:

json
{
  "status": "success",
  "message": "pong",
  "authenticated": true,
  "api_key_id": "key_abc123"
}

Check Permissions

Test specific permission levels:

bash
# Test read permission
curl -H "Authorization: Bearer YOUR_API_KEY" \
     https://api.0link.com/v2/account

# Test write permission
curl -X POST \
     -H "Authorization: Bearer YOUR_API_KEY" \
     -H "Content-Type: application/json" \
     -d '{"name":"Test Project"}' \
     https://api.0link.com/v2/projects

SDK Authentication

JavaScript SDK

javascript
import { ZeroLink } from '@0link/sdk';

const client = new ZeroLink({
  apiKey: process.env.ZEROLINK_API_KEY,
  environment: 'production' // or 'development'
});

// SDK handles authentication automatically
const account = await client.account.get();

Python SDK

python
import os
from zerolink import Client

client = Client(
    api_key=os.getenv('ZEROLINK_API_KEY'),
    environment='production'
)

# SDK handles authentication automatically
account = client.account.get()

Webhook Authentication

Verify webhook signatures to ensure requests come from 0.link:

Signature Verification

javascript
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')
  );
}

// In your webhook handler
const payload = req.body;
const signature = req.headers['x-0link-signature'];
const isValid = verifyWebhookSignature(payload, signature, webhookSecret);

if (!isValid) {
  return res.status(401).send('Invalid signature');
}

Security Considerations

Transport Security

  • ✅ Always use HTTPS for API requests
  • ✅ Verify SSL certificates in production
  • ❌ Never use HTTP in production

Key Management

  • ✅ Store keys securely (environment variables, key vaults)
  • ✅ Rotate keys regularly (every 90 days)
  • ✅ Use different keys for different environments
  • ✅ Monitor key usage for anomalies
  • ❌ Never log API keys
  • ❌ Never share keys via email or chat

Application Security

javascript
// ✅ Good: Secure key handling
const apiKey = process.env.ZEROLINK_API_KEY;
if (!apiKey) {
  throw new Error('API key not configured');
}

const client = new ZeroLink({ apiKey });

// ❌ Bad: Exposed key
const client = new ZeroLink({
  apiKey: '0link_sk_1234...' // Hardcoded key
});

// ❌ Bad: Logging keys
console.log('Using API key:', apiKey); // Never log keys

Monitoring and Alerting

Track Authentication Events

Monitor for unusual authentication patterns:

  • Multiple failed authentication attempts
  • API keys used from unexpected locations
  • Sudden spikes in API usage
  • New API keys created

Set Up Alerts

Configure alerts for security events:

json
{
  "alert_conditions": [
    {
      "name": "Failed Authentication",
      "condition": "failed_auth_attempts > 10 in 5 minutes",
      "action": "email_admin"
    },
    {
      "name": "New Geographic Location",
      "condition": "api_key_used_from_new_country",
      "action": "email_admin"
    }
  ]
}

Troubleshooting

Common Issues

"Invalid API Key" Errors

  • Verify key is copied correctly (no extra spaces)
  • Check key hasn't been deleted in dashboard
  • Ensure you're using the secret key (sk_) not a placeholder

"Forbidden" Errors

  • Check API key permissions in dashboard
  • Verify your account plan supports the feature
  • Ensure you're using the correct endpoint

Intermittent Authentication Failures

  • Check for network connectivity issues
  • Verify system clock is synchronized
  • Look for rate limiting responses

Debug Mode

Enable debug logging to troubleshoot authentication:

javascript
const client = new ZeroLink({
  apiKey: process.env.ZEROLINK_API_KEY,
  debug: true // Enable debug logging
});

Contact Support

For authentication issues:

Next Steps