Skip to content
Last updated: 2026-04-06
Reference

DX API Authentication

Secure API access using JWT tokens and API keys for Dxtra's privacy compliance API.

Quick Start

Prerequisite: Dxtra account with API access enabled Result: Working JWT token for API calls

Authentication Flow

Dxtra uses a two-step authentication process:

  1. API Key to JWT Exchange -- Trade your long-lived API key for a short-lived JWT token
  2. JWT Token Usage -- Use JWT in Authorization headers for all API calls
sequenceDiagram
    participant Client
    participant Auth as auth.dxtra.ai
    participant API as api.dxtra.ai

    Client->>Auth: POST /v1/signin/pat<br/>{personalAccessToken}
    Auth->>Client: JWT token (1 hour expiry)
    Client->>API: GraphQL Query<br/>Authorization: Bearer JWT
    API->>Client: Response data

Setup

Step 1: Get Your API Key

  1. Login to Dxtra Dashboard
  2. Navigate to Developers in the top bar
  3. Click "Create API Key"
  4. Copy and securely store your API key

Security

API keys are shown only once during generation. Store securely and never commit to version control.

Step 2: Exchange for JWT Token

JavaScript
const getJwtToken = async (apiKey) => {
  const response = await fetch('https://auth.dxtra.ai/v1/signin/pat', {
    method: 'POST',
    headers: {
      'Content-Type': 'application/json',
    },
    body: JSON.stringify({
      personalAccessToken: apiKey
    })
  });

  if (!response.ok) {
    throw new Error(`Authentication failed: ${response.status}`);
  }

  const data = await response.json();
  return data.session.accessToken;
};

// Usage
const jwt = await getJwtToken(process.env.DXTRA_API_KEY);
Python
import requests
import os

def get_jwt_token(api_key):
    """Exchange API key for JWT token"""
    response = requests.post(
        'https://auth.dxtra.ai/v1/signin/pat',
        headers={'Content-Type': 'application/json'},
        json={'personalAccessToken': api_key}
    )

    if response.status_code != 200:
        raise Exception(f'Authentication failed: {response.status_code}')

    return response.json()['session']['accessToken']

# Usage
jwt_token = get_jwt_token(os.getenv('DXTRA_API_KEY'))
Bash
# Get JWT token
JWT_TOKEN=$(curl -s -X POST "https://auth.dxtra.ai/v1/signin/pat" \
  -H "Content-Type: application/json" \
  -d '{"personalAccessToken":"'$DXTRA_API_KEY'"}' \
  | jq -r '.session.accessToken')

echo "JWT Token obtained: ${JWT_TOKEN:0:20}..."

Step 3: Use JWT for API Calls

JavaScript
import { GraphQLClient } from 'graphql-request';

const client = new GraphQLClient('https://api.dxtra.ai/v1/graphql', {
  headers: {
    'Authorization': `Bearer ${jwt}`,
    'X-Hasura-Role': 'user'
  }
});

const query = `{
  dataControllers {
    id
    title
    createdAt
  }
}`;

const data = await client.request(query);
Python
def authenticated_request(jwt_token, query, variables=None):
    response = requests.post(
        'https://api.dxtra.ai/v1/graphql',
        headers={
            'Authorization': f'Bearer {jwt_token}',
            'X-Hasura-Role': 'user',
            'Content-Type': 'application/json'
        },
        json={
            'query': query,
            'variables': variables or {}
        }
    )
    return response.json()
Bash
curl -X POST "https://api.dxtra.ai/v1/graphql" \
  -H "Authorization: Bearer $JWT_TOKEN" \
  -H "X-Hasura-Role: user" \
  -H "Content-Type: application/json" \
  -d '{"query": "{ dataControllers { id title createdAt } }"}'

Token Management

Token Type Duration Purpose
Access Token (JWT) 1 hour API calls and GraphQL queries
Refresh Token 12 hours Obtain new access tokens
Personal Access Token Variable Initial authentication (managed in Dashboard)

When an access token expires, you receive a 401 Unauthorized response. Re-authenticate with your Personal Access Token to get a new JWT.

Role-Based Access

Use the X-Hasura-Role header to specify access level:

Role Access Level Use Case
user Standard data access Dashboard and management operations
me Personal user data User profile and personal settings operations
dataSubject Individual privacy data Privacy center and transparency portal
anonymous Public access Consent tracking, event tracking, public widgets

Environment Configuration

Bash
# Production endpoints
AUTH_URL=https://auth.dxtra.ai/v1/signin/pat
API_URL=https://api.dxtra.ai/v1/graphql

Error Handling

Common Authentication Errors

Error Code Cause Solution
400 Invalid API key format Verify API key copied correctly
401 API key not found or expired Regenerate API key in Dashboard
403 Insufficient permissions Check X-Hasura-Role header
429 Rate limit exceeded Implement exponential backoff

Retry with Exponential Backoff

JavaScript
const authenticateWithRetry = async (apiKey, maxRetries = 3) => {
  for (let attempt = 1; attempt <= maxRetries; attempt++) {
    try {
      return await getJwtToken(apiKey);
    } catch (error) {
      if (attempt === maxRetries) throw error;

      const delay = Math.pow(2, attempt) * 1000;
      await new Promise(resolve => setTimeout(resolve, delay));
    }
  }
};
Python
import time
import random

def authenticate_with_retry(api_key, max_retries=3):
    for attempt in range(1, max_retries + 1):
        try:
            return get_jwt_token(api_key)
        except Exception as e:
            if attempt == max_retries:
                raise e

            # Exponential backoff with jitter
            delay = (2 ** attempt) + random.uniform(0, 1)
            time.sleep(delay)

Security Best Practices

API Key Management

  • Environment Variables -- Store API keys in environment variables, never in code
  • Rotation Schedule -- Rotate API keys regularly
  • Access Control -- Limit API key access to minimum required personnel
  • Monitoring -- Monitor API key usage for suspicious activity

JWT Token Security

  • Short-Lived -- JWT tokens expire in 1 hour (3600s); implement proactive refresh
  • Secure Storage -- Store in memory only, avoid localStorage for sensitive applications
  • Network Security -- Always use HTTPS for authentication and API calls
  • Logging -- Never log JWT tokens in application logs

Production Checklist

  • API keys stored in secure environment variables
  • JWT tokens refreshed before expiry
  • Error handling implemented for all authentication scenarios
  • Rate limiting respected with exponential backoff
  • Security monitoring enabled for API access

Troubleshooting

Token Validation

Bash
# Decode JWT to verify claims (requires jwt CLI tool)
echo "$JWT_TOKEN" | jwt decode -

# Check token expiry
echo "$JWT_TOKEN" | jwt decode - | jq '.exp'

Connection Testing

Bash
# Test auth endpoint connectivity
curl -I https://auth.dxtra.ai/v1/signin/pat

# Test API endpoint connectivity
curl -I https://api.dxtra.ai/v1/graphql

Next Steps