7 min read

Authentication

Secure authentication methods for the DocuRift API using API keys and session tokens

DocuRift API supports two authentication methods: API Keys for programmatic access and Session Tokens for web dashboard access. All API requests must be authenticated using one of these methods.

Authentication Methods

API Key Authentication

API keys provide secure, programmatic access to the DocuRift API. They are ideal for server-to-server communication, automated workflows, and integrations.

Using API Keys

Include your API key in the X-API-Key header with every request:

curl -X GET https://api.docurift.com/v1/documents \
  -H "X-API-Key: frc_abc123def456ghi789jkl012mno345pq"

API Key Format

All API keys follow a consistent format:

  • Prefix: frc_ (DocuRift identifier)
  • Length: 36 characters total (prefix + 32 random characters)
  • Example: frc_abc123def456ghi789jkl012mno345pq

Key Storage & Security

For security, DocuRift implements the following measures:

  1. SHA-256 Hashing: API keys are hashed using SHA-256 before storage
  2. One-time Display: The full key is shown only once during creation
  3. Prefix Visibility: Only the first 12 characters (e.g., frc_abc123de...) are visible after creation
  4. Last Used Tracking: Every API request updates the lastUsedAt timestamp

Key Permissions

API keys inherit permissions from the organization they belong to:

  • Organization-scoped: Keys are tied to a specific organization
  • Admin-only Creation: Only organization owners and admins can create API keys
  • Full API Access: Keys have access to all API endpoints within the organization

Session Authentication

Session tokens are used for web dashboard access and are automatically managed by the DocuRift authentication system.

Using Session Tokens

Session tokens can be provided in two ways:

1. Authorization Header (Recommended for API clients):

curl -X GET https://api.docurift.com/v1/documents \
  -H "Authorization: Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9..."

2. Cookie-based (Automatic for web browsers):

curl -X GET https://api.docurift.com/v1/documents \
  -H "Cookie: session_token=eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9..." \
  --cookie-jar cookies.txt

Session Expiry

Sessions expire after a period of inactivity. When a session expires:

  • Status code: 401 Unauthorized
  • Error code: SESSION_EXPIRED
  • Action required: Re-authenticate to obtain a new session token

Security Features

IP-based Rate Limiting

DocuRift implements aggressive protection against brute-force attacks:

Invalid Key Attempts

  • Threshold: 25 invalid API key attempts
  • Block Duration: 24 hours
  • Scope: Per IP address
  • Applies to: Both invalid and expired keys

Block Behavior

When an IP is blocked:

  • Status code: 403 Forbidden
  • Error code: IP_BLOCKED
  • All requests from that IP are rejected
  • Automatic unblock after 24 hours

Attempt Counter

Failed authentication attempts return:

{
  "success": false,
  "error": {
    "code": "INVALID_API_KEY",
    "message": "Invalid API key. 22 attempts remaining before IP block."
  }
}

Key Expiration

API keys support optional expiration dates:

  • Set expiresAt when creating a key
  • Expired keys are automatically rejected
  • Failed attempts with expired keys count toward IP blocking

Last Used Tracking

Every successful API request updates the key's lastUsedAt timestamp, allowing you to:

  • Monitor key usage patterns
  • Identify unused keys for cleanup
  • Detect potentially compromised keys

Code Examples

cURL

# Using API Key
curl -X POST https://api.docurift.com/v1/documents/process \
  -H "X-API-Key: frc_your_api_key_here" \
  -F "file=@document.pdf" \
  -F "documentType=invoice"

# Using Session Token
curl -X GET https://api.docurift.com/v1/credits/balance \
  -H "Authorization: Bearer your_session_token_here"

Python (requests)

import requests
import os

# Best practice: Load API key from environment
API_KEY = os.getenv('DOCURIFT_API_KEY')
API_URL = 'https://api.docurift.com/v1'

# Using API Key
headers = {
    'X-API-Key': API_KEY
}

# Upload document
with open('invoice.pdf', 'rb') as f:
    files = {'file': f}
    data = {'documentType': 'invoice'}
    response = requests.post(
        f'{API_URL}/documents/process',
        headers=headers,
        files=files,
        data=data
    )

result = response.json()
print(result)

# Check balance
response = requests.get(
    f'{API_URL}/credits/balance',
    headers=headers
)
balance = response.json()
print(f"Credits remaining: {balance['data']['balance']}")

JavaScript (fetch)

// Best practice: Load API key from environment
const API_KEY = process.env.DOCURIFT_API_KEY;
const API_URL = 'https://api.docurift.com/v1';

// Using API Key
const headers = {
  'X-API-Key': API_KEY
};

// Upload document
const formData = new FormData();
formData.append('file', fileInput.files[0]);
formData.append('documentType', 'invoice');

const response = await fetch(`${API_URL}/documents/process`, {
  method: 'POST',
  headers: headers,
  body: formData
});

const result = await response.json();
console.log(result);

// List documents
const listResponse = await fetch(`${API_URL}/documents`, {
  headers: {
    'X-API-Key': API_KEY,
    'Content-Type': 'application/json'
  }
});

const documents = await listResponse.json();
console.log(documents);

Node.js (with axios)

import axios from 'axios';
import FormData from 'form-data';
import fs from 'fs';

const api = axios.create({
  baseURL: 'https://api.docurift.com/v1',
  headers: {
    'X-API-Key': process.env.DOCURIFT_API_KEY
  }
});

// Upload document
async function uploadDocument(filePath) {
  const form = new FormData();
  form.append('file', fs.createReadStream(filePath));
  form.append('documentType', 'invoice');

  try {
    const response = await api.post('/documents/process', form, {
      headers: form.getHeaders()
    });
    return response.data;
  } catch (error) {
    console.error('Upload failed:', error.response?.data);
    throw error;
  }
}

// Get document by ID
async function getDocument(documentId) {
  try {
    const response = await api.get(`/documents/${documentId}`);
    return response.data;
  } catch (error) {
    console.error('Failed to fetch document:', error.response?.data);
    throw error;
  }
}

Error Responses

Common Authentication Errors

401 Unauthorized - Missing Authentication

{
  "success": false,
  "error": {
    "code": "UNAUTHORIZED",
    "message": "Authentication required"
  }
}

Cause: No API key or session token provided Solution: Include X-API-Key header or Authorization: Bearer header


401 Unauthorized - Invalid API Key

{
  "success": false,
  "error": {
    "code": "INVALID_API_KEY",
    "message": "Invalid API key. 20 attempts remaining before IP block."
  }
}

Cause: API key doesn't exist or is malformed Solution: Verify your API key is correct and hasn't been deleted


401 Unauthorized - Expired API Key

{
  "success": false,
  "error": {
    "code": "INVALID_API_KEY",
    "message": "API key has expired"
  }
}

Cause: API key expiration date has passed Solution: Generate a new API key from the dashboard


403 Forbidden - IP Blocked

{
  "success": false,
  "error": {
    "code": "IP_BLOCKED",
    "message": "Your IP has been temporarily blocked due to multiple invalid API key attempts"
  }
}

Cause: 25+ failed authentication attempts from your IP Solution: Wait 24 hours or contact support if this was an error


401 Unauthorized - Session Expired

{
  "success": false,
  "error": {
    "code": "SESSION_EXPIRED",
    "message": "Session expired or invalid"
  }
}

Cause: Session token has expired or is invalid Solution: Re-authenticate through the web dashboard


403 Forbidden - Admin Access Required

{
  "success": false,
  "error": {
    "code": "FORBIDDEN",
    "message": "Admin access required to create API keys"
  }
}

Cause: Attempting to create/manage API keys without admin privileges Solution: Contact your organization owner for API key management

Best Practices

Environment Variables

Never hardcode API keys in your source code. Use environment variables:

# .env file
DOCURIFT_API_KEY=frc_your_api_key_here
# Python
import os
api_key = os.getenv('DOCURIFT_API_KEY')
// Node.js
const apiKey = process.env.DOCURIFT_API_KEY;

Key Rotation

Regularly rotate API keys for enhanced security:

  1. Create a new API key
  2. Update all applications with the new key
  3. Monitor the old key's lastUsedAt to ensure no active usage
  4. Delete the old key after verification

Key Management

  • Name your keys descriptively: production-server, staging-env, ci-cd-pipeline
  • Set expiration dates for temporary access
  • Deactivate unused keys instead of immediate deletion
  • Monitor last used timestamps to identify stale keys

Error Handling

Implement robust error handling for authentication failures:

async function makeAuthenticatedRequest(endpoint) {
  try {
    const response = await fetch(endpoint, {
      headers: { 'X-API-Key': API_KEY }
    });

    if (!response.ok) {
      const error = await response.json();

      switch (error.error.code) {
        case 'INVALID_API_KEY':
          console.error('API key is invalid or expired');
          break;
        case 'IP_BLOCKED':
          console.error('IP blocked due to too many failed attempts');
          break;
        case 'UNAUTHORIZED':
          console.error('Authentication required');
          break;
        default:
          console.error('Request failed:', error.error.message);
      }

      throw new Error(error.error.message);
    }

    return await response.json();
  } catch (error) {
    console.error('Request failed:', error);
    throw error;
  }
}

Next Steps