Authentication

AS2aaS uses API key authentication for all API requests. This guide covers how to obtain, manage, and use API keys securely with the account-based architecture supporting both account-level and tenant-level operations.

API Keys

Key Types

AS2aaS provides API keys with two environment types and two scope levels:

Environment Types:

  • Test Keys (pk_test_..., tk_test_...) - For development and testing
  • Live Keys (pk_live_..., tk_live_...) - For production messaging

Scope Levels:

  • Account-Scoped Keys - Access multiple tenants within an account (enterprise-focused)
  • Tenant-Scoped Keys - Access single tenant only (application-focused)

Key Prefixes and Scoping

Key TypePrefixScopeAccess Level
Account Testpk_test_Account-wideAll tenants in account (test mode)
Account Livepk_live_Account-wideAll tenants in account (production)
Tenant Testtk_test_Single tenantSpecific tenant only (test mode)
Tenant Livetk_live_Single tenantSpecific tenant only (production)

Test vs Live Environment

FeatureTest EnvironmentLive Environment
Message SendingSimulated (no real transmission)Real AS2 messages sent
Message ReceivingSandbox simulation availableReal messages from partners
Usage BillingFree (no charges)Counts toward plan limits
Partner TestingSafe testing environmentReal partner interactions
WebhooksTest webhook deliveryProduction webhook delivery
Master PartnersTest master partner configurationsProduction master partners

Account-Scoped vs Tenant-Scoped Keys

FeatureAccount-Scoped KeysTenant-Scoped Keys
AccessMultiple tenants within accountSingle tenant only
Master PartnersCan create and manage master partnersCan view inherited master partners (read-only)
Tenant ManagementCan create and manage tenantsCannot access tenant management
Multi-Tenant OperationsSend messages for any tenant in accountLimited to single tenant
BillingAccount-level usage trackingTenant-level usage attribution
Use CaseEnterprise administration, multi-tenant appsSingle-tenant applications, microservices
SecurityCan be restricted to specific tenantsInherently restricted to one tenant

Getting API Keys

1. Create Account

First, register for an AS2aaS account:

POST /auth/register

Request:

{
  "name": "John Doe",
  "email": "[email protected]",
  "password": "SecurePass123",
  "password_confirmation": "SecurePass123"
}

Response (201):

{
  "message": "User registered successfully",
  "user": {
    "id": 1,
    "name": "John Doe",
    "email": "[email protected]"
  },
  "tenant": {
    "id": 1,
    "name": "John Doe's Organization",
    "pricing_tier": "free"
  },
  "token": "1|abc123def456..."
}

2. Login to Dashboard

POST /auth/login

Request:

{
  "email": "[email protected]",
  "password": "SecurePass123"
}

3. Generate API Keys

POST /v1/api-keys

Account-Scoped Key:

{
  "name": "My Account Test Key",
  "scope": "account",
  "environment": "test",
  "permissions": ["*"]
}

Tenant-Scoped Key:

{
  "name": "My Tenant Test Key",
  "scope": "tenant",
  "tenant_id": "tnt_000001",
  "environment": "test",
  "permissions": ["messages:read", "messages:write", "partners:read"]
}

Response (201):

{
  "message": "API key created successfully",
  "data": {
    "id": "key_000001",
    "name": "My Account Test Key", 
    "key": "pk_test_abc123def456ghi789jkl012mno345pqr678stu901",
    "key_prefix": "pk_test_",
    "scope": "account",
    "environment": "test",
    "permissions": ["*"],
    "created_at": "2024-01-15T10:30:00Z"
  }
}

Using API Keys

Basic Authentication

Include your API key in the Authorization header:

curl -X GET https://api.as2aas.com/v1/partners \
  -H "Authorization: Bearer pk_test_abc123def456ghi789jkl012mno345pqr678stu901"

Required Headers

Authorization: Bearer YOUR_API_KEY
Content-Type: application/json
Accept: application/json

Optional Headers

X-Tenant-ID: tnt_000001           # Switch tenant context (account-scoped keys only)
Idempotency-Key: unique-uuid      # Prevent duplicate operations

Tenant Context with Different Key Types

Account-Scoped Keys

# Default tenant (first tenant in account)
curl -H "Authorization: Bearer pk_live_account_key" \
  https://api.as2aas.com/v1/partners

# Specific tenant
curl -H "Authorization: Bearer pk_live_account_key" \
     -H "X-Tenant-ID: tnt_000002" \
  https://api.as2aas.com/v1/partners

Tenant-Scoped Keys

# Automatically scoped to associated tenant
curl -H "Authorization: Bearer tk_live_tenant_key" \
  https://api.as2aas.com/v1/partners
# X-Tenant-ID header ignored for tenant-scoped keys

API Key Management

List API Keys

GET /v1/api-keys

Response (200):

{
  "data": [
    {
      "id": "key_000001",
      "name": "Production API Key",
      "key_prefix": "pk_live_",
      "environment": "live",
      "scopes": ["*"],
      "last_used_at": "2024-01-15T10:30:00Z",
      "expires_at": null,
      "created_at": "2024-01-01T10:00:00Z"
    },
    {
      "id": "key_000002",
      "name": "Test API Key",
      "key_prefix": "pk_test_",
      "environment": "test", 
      "scopes": ["*"],
      "last_used_at": "2024-01-15T09:15:00Z",
      "expires_at": "2025-01-01T00:00:00Z",
      "created_at": "2024-01-01T10:00:00Z"
    }
  ]
}

Create API Key

POST /v1/api-keys

Request:

{
  "name": "My Production Key",
  "environment": "live",
  "scopes": ["*"],
  "expires_at": "2025-12-31T23:59:59Z"
}

Delete API Key

DELETE /v1/api-keys/{key_id}

Scopes and Permissions

Available Permissions

Account-Level Permissions (Account-Scoped Keys)

PermissionDescription
*Full account access
accounts:readRead account information
accounts:writeManage account settings
tenants:readRead tenant information
tenants:writeCreate and manage tenants
users:readRead user information
users:writeManage account users
billing:readRead billing information
billing:writeManage billing and subscriptions

Tenant-Level Permissions (Both Key Types)

PermissionDescription
*Full tenant access
messages:readRead message data
messages:writeSend messages
partners:readRead partner data
partners:writeManage tenant partners
certificates:readRead certificates
certificates:writeManage certificates
webhooks:readRead webhook configurations
webhooks:writeManage webhooks

Permission Examples

Account-Level Administrative Key

{
  "name": "Account Admin Key",
  "scope": "account",
  "environment": "live",
  "permissions": [
    "accounts:read",
    "accounts:write",
    "tenants:read",
    "tenants:write",
    "users:read",
    "users:write"
  ]
}

Tenant-Level Integration Key

{
  "name": "Read-Only Integration Key",
  "scope": "tenant",
  "tenant_id": "tnt_000001",
  "environment": "live",
  "permissions": [
    "messages:read",
    "partners:read",
    "certificates:read"
  ]
}

Multi-Tenant Application Key

{
  "name": "Multi-Tenant App Key",
  "scope": "account",
  "environment": "live",
  "permissions": [
    "messages:read",
    "messages:write",
    "partners:read"
  ]
}

Multi-Tenant Authentication

Tenant Context

API keys are associated with a specific tenant (organization). Use the X-Tenant-ID header to switch between tenants if you have access to multiple:

curl -X GET https://api.as2aas.com/v1/partners \
  -H "Authorization: Bearer YOUR_API_KEY" \
  -H "X-Tenant-ID: tnt_000002"

List User Tenants

GET /auth/me

Response (200):

{
  "user": {
    "id": 1,
    "name": "John Doe",
    "email": "[email protected]"
  },
  "tenants": [
    {
      "id": 1,
      "name": "Primary Organization",
      "slug": "primary-org",
      "role": "owner",
      "pricing_tier": "starter"
    },
    {
      "id": 2,
      "name": "Secondary Organization", 
      "slug": "secondary-org",
      "role": "admin",
      "pricing_tier": "free"
    }
  ]
}

Security Best Practices

API Key Security

  1. Store Securely: Never commit API keys to version control
  2. Use Environment Variables: Store keys in environment variables
  3. Rotate Regularly: Create new keys and delete old ones periodically
  4. Scope Appropriately: Use minimal required scopes
  5. Monitor Usage: Review API key usage logs regularly

Environment Separation

# Development environment
export AS2AAS_API_KEY="pk_test_abc123..."

# Production environment  
export AS2AAS_API_KEY="pk_live_xyz789..."

Key Rotation

// Rotate API keys safely
async function rotateApiKey(oldKeyId, newKeyName) {
  // Create new key
  const newKey = await as2.apiKeys.create({
    name: newKeyName,
    environment: 'live',
    scopes: ['*']
  });
  
  // Update application configuration
  await updateEnvironmentVariable('AS2AAS_API_KEY', newKey.key);
  
  // Test new key
  await as2.setApiKey(newKey.key);
  const testResult = await as2.partners.list();
  
  if (testResult.data) {
    // Delete old key
    await as2.apiKeys.delete(oldKeyId);
    console.log('API key rotated successfully');
  } else {
    throw new Error('New API key test failed');
  }
}

Rate Limiting

Rate Limit Headers

All API responses include rate limit information:

HTTP/1.1 200 OK
X-RateLimit-Limit: 300
X-RateLimit-Remaining: 299
X-RateLimit-Reset: 1642262400
X-RateLimit-Retry-After: 60

Rate Limits by Plan

PlanRequests per minute
Free100
Starter300
Professional1000
EnterpriseCustom

Handling Rate Limits

async function makeApiRequest(url, options) {
  try {
    const response = await fetch(url, options);
    
    if (response.status === 429) {
      // Rate limited - wait and retry
      const retryAfter = response.headers.get('X-RateLimit-Retry-After');
      await new Promise(resolve => setTimeout(resolve, retryAfter * 1000));
      return makeApiRequest(url, options); // Retry
    }
    
    return response;
  } catch (error) {
    console.error('API request failed:', error);
    throw error;
  }
}

Error Responses

Authentication Errors

Invalid API Key:

{
  "error": {
    "type": "authentication_error",
    "code": "invalid_api_key",
    "message": "The provided API key is invalid or has been revoked"
  }
}

Expired API Key:

{
  "error": {
    "type": "authentication_error",
    "code": "expired_api_key", 
    "message": "API key expired on 2024-01-01T00:00:00Z"
  }
}

Insufficient Permissions:

{
  "error": {
    "type": "authorization_error",
    "code": "insufficient_scope",
    "message": "API key does not have required scope: messages:write"
  }
}

Testing Authentication

Verify API Key

curl -X GET https://api.as2aas.com/v1/api-keys \
  -H "Authorization: Bearer YOUR_API_KEY"

If successful, your API key is valid and you'll see your key list.

Test Different Environments

# Test with test key
curl -X GET https://api.as2aas.com/v1/partners \
  -H "Authorization: Bearer pk_test_..."

# Test with live key
curl -X GET https://api.as2aas.com/v1/partners \
  -H "Authorization: Bearer pk_live_..."

SDK Authentication

Node.js SDK

const AS2aaS = require('as2aas');

// Initialize with API key
const as2 = new AS2aaS('pk_test_your_api_key');

// Or set environment variable
// AS2AAS_API_KEY=pk_test_your_api_key
const as2 = new AS2aaS();

Python SDK

import as2aas

# Initialize with API key
as2 = as2aas.Client('pk_test_your_api_key')

# Or use environment variable
# export AS2AAS_API_KEY=pk_test_your_api_key
as2 = as2aas.Client()

PHP SDK

<?php
use AS2aaS\Client;

// Initialize with API key
$as2 = new Client('pk_test_your_api_key');

// Or use environment variable
// AS2AAS_API_KEY=pk_test_your_api_key
$as2 = new Client();

Troubleshooting

Common Authentication Issues

401 Unauthorized

  • Check API key format (starts with pk_test_ or pk_live_)
  • Verify key hasn't been deleted or expired
  • Ensure Authorization header format: Bearer YOUR_KEY

403 Forbidden

  • Check API key scopes match required permissions
  • Verify tenant access if using multi-tenant setup
  • Ensure account is active and in good standing

429 Rate Limited

  • Reduce request frequency
  • Implement exponential backoff
  • Consider upgrading to higher plan

Debug Authentication

# Test API key validity
curl -v -X GET https://api.as2aas.com/v1/api-keys \
  -H "Authorization: Bearer pk_test_your_key"

# Check response headers for rate limit info
# Look for X-RateLimit-* headers

Getting Help

For authentication issues:

  1. Verify API key in your dashboard
  2. Check key scopes and permissions
  3. Review error messages for specific issues
  4. Contact support with API key ID (not the full key)