> ## Documentation Index
> Fetch the complete documentation index at: https://docs.credprotocol.com/llms.txt
> Use this file to discover all available pages before exploring further.

# Authentication Guide

> Complete guide to authenticating with the Cred Protocol API

## Overview

This guide covers everything you need to know about authenticating with the Cred Protocol API, from creating API keys to implementing secure authentication in your applications.

## Authentication Methods

The Cred Protocol API supports two authentication methods:

### 1. API Key Authentication (Recommended)

The standard authentication method using Bearer tokens. Every request includes your API key in the `Authorization` header. Usage is tracked against your subscription's Cred Unit balance.

```bash theme={null}
Authorization: Bearer YOUR_API_KEY
```

### 2. x402 Payment Authentication (No Account Required)

For instant access without creating an account, you can pay per request using USDC stablecoins via the [x402 protocol](https://docs.cdp.coinbase.com/x402/welcome). This enables accountless API access with immediate settlement.

```bash theme={null}
X-PAYMENT: <signed_payment_payload>
```

<Info>
  x402 payments support USDC on Base and SKALE networks. Facilitators include the Coinbase Developer Platform (CDP) for Base and the dirtroad.dev facilitator for SKALE.
</Info>

## Creating API Keys

### Step-by-Step Guide

<Steps>
  <Step title="Sign In">
    Go to [app.credprotocol.com](https://app.credprotocol.com) and sign in to your account.
  </Step>

  <Step title="Navigate to Dashboard">
    Click on **Dashboard** in the navigation menu.
  </Step>

  <Step title="Access API Keys">
    Find the **API Keys** section in your dashboard.
  </Step>

  <Step title="Create New Key">
    Click **Create API Key** and enter a descriptive name for your key.

    <Tip>
      Use descriptive names like "Production Server", "Development", or "CI/CD Pipeline" to easily identify keys later.
    </Tip>
  </Step>

  <Step title="Copy and Store Securely">
    Copy your API key immediately and store it securely. You won't be able to view the full key again.

    <Warning>
      Never share your API key or commit it to version control.
    </Warning>
  </Step>
</Steps>

## Implementation Examples

### Environment Variables

Always store your API key in environment variables:

<CodeGroup>
  ```bash .env theme={null}
  CRED_API_KEY=your_api_key_here
  ```

  ```javascript Node.js theme={null}
  // Load from environment
  const API_KEY = process.env.CRED_API_KEY;

  const response = await fetch('https://api.credprotocol.com/api/v2/score/address/vitalik.eth', {
    headers: {
      'Authorization': `Bearer ${API_KEY}`
    }
  });
  ```

  ```python Python theme={null}
  import os
  import requests

  API_KEY = os.environ.get('CRED_API_KEY')

  response = requests.get(
      'https://api.credprotocol.com/api/v2/score/address/vitalik.eth',
      headers={'Authorization': f'Bearer {API_KEY}'}
  )
  ```
</CodeGroup>

### Backend Proxy Pattern

For web applications, create a backend proxy to keep your API key secure:

<CodeGroup>
  ```javascript Next.js API Route theme={null}
  // pages/api/credit-score.js
  export default async function handler(req, res) {
    const { address } = req.query;
    
    const response = await fetch(
      `https://api.credprotocol.com/api/v2/score/address/${address}`,
      {
        headers: {
          'Authorization': `Bearer ${process.env.CRED_API_KEY}`
        }
      }
    );
    
    const data = await response.json();
    res.status(response.status).json(data);
  }
  ```

  ```javascript Frontend theme={null}
  // Call your backend proxy, not the Cred API directly
  const response = await fetch(`/api/credit-score?address=${address}`);
  const data = await response.json();
  ```
</CodeGroup>

### SDK Pattern

Create a reusable client for your application:

```typescript theme={null}
// lib/cred-client.ts
class CredClient {
  private apiKey: string;
  private baseUrl = 'https://api.credprotocol.com';

  constructor(apiKey: string) {
    this.apiKey = apiKey;
  }

  private async request(endpoint: string) {
    const response = await fetch(`${this.baseUrl}${endpoint}`, {
      headers: {
        'Authorization': `Bearer ${this.apiKey}`,
        'Content-Type': 'application/json'
      }
    });

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

    return response.json();
  }

  async getScore(address: string) {
    return this.request(`/api/v2/score/address/${address}`);
  }

  async getReport(address: string) {
    return this.request(`/api/v2/report/address/${address}`);
  }

  async getIdentity(address: string) {
    return this.request(`/api/v2/identity/address/${address}/attestations`);
  }
}

// Usage
const cred = new CredClient(process.env.CRED_API_KEY!);
const score = await cred.getScore('vitalik.eth');
```

## Security Best Practices

<AccordionGroup>
  <Accordion title="Never expose keys in client-side code">
    API keys should never be included in frontend JavaScript, mobile apps, or anywhere they can be viewed by end users.

    ```javascript theme={null}
    // ❌ NEVER do this
    const response = await fetch('https://api.credprotocol.com/api/v2/score/address/vitalik.eth', {
      headers: { 'Authorization': 'Bearer sk_live_abc123' }
    });

    // ✅ Call your backend instead
    const response = await fetch('/api/credit-score?address=vitalik.eth');
    ```
  </Accordion>

  <Accordion title="Use environment variables">
    Store API keys in environment variables, never in code:

    * Use `.env` files for local development
    * Use secret management services in production (AWS Secrets Manager, HashiCorp Vault, etc.)
    * Never commit `.env` files to version control
  </Accordion>

  <Accordion title="Rotate keys regularly">
    Establish a key rotation schedule:

    1. Create a new API key
    2. Update your application to use the new key
    3. Verify the new key works in production
    4. Revoke the old key
  </Accordion>

  <Accordion title="Use separate keys for environments">
    Create different API keys for:

    * Development
    * Staging
    * Production

    This limits the impact if a key is compromised and makes auditing easier.
  </Accordion>

  <Accordion title="Monitor key usage">
    Regularly review your API usage in the Dashboard to:

    * Detect unusual activity patterns
    * Identify compromised keys
    * Optimize your usage
  </Accordion>
</AccordionGroup>

## Troubleshooting

### Common Errors

<AccordionGroup>
  <Accordion title="401 Unauthorized">
    ```json theme={null}
    { "detail": "Invalid or missing API key" }
    ```

    **Possible causes:**

    * API key is missing from the request
    * API key is malformed
    * API key has been revoked

    **Solutions:**

    * Verify the `Authorization` header is present
    * Check for typos in the API key
    * Ensure you're using `Bearer ` prefix (with space)
    * Create a new API key if needed
  </Accordion>

  <Accordion title="403 Forbidden">
    ```json theme={null}
    { "detail": "Insufficient permissions" }
    ```

    **Possible causes:**

    * Accessing a feature not included in your plan
    * Rate limit exceeded

    **Solutions:**

    * Check your plan limits in the Dashboard
    * Upgrade your plan if needed
    * Implement rate limiting in your application
  </Accordion>
</AccordionGroup>

### Testing Your API Key

Use this simple test to verify your API key is working:

```bash theme={null}
curl -X GET "https://api.credprotocol.com/users/me" \
  -H "Authorization: Bearer YOUR_API_KEY"
```

A successful response confirms your key is valid:

```json theme={null}
{
  "id": "uuid",
  "email": "you@example.com",
  "is_active": true
}
```

## x402 Payment Authentication

The x402 protocol enables instant API access by paying per request with USDC. This is ideal for:

* **Testing** the API before committing to a subscription
* **Low-volume usage** where a subscription isn't cost-effective
* **Programmatic access** from applications that can't store API keys
* **Instant access** without account creation or approval delays

### How It Works

1. Make a request without authentication
2. Receive a `402 Payment Required` response with payment details
3. Sign a USDC transfer authorization using your wallet
4. Retry the request with the signed payment in the `X-PAYMENT` header
5. Receive your API response (payment settles automatically)

### Payment Required Response

When you make a request without authentication, you'll receive:

```json theme={null}
{
  "error": "authentication_required",
  "message": "This endpoint requires authentication. Choose one of the following methods:",
  "cred_units": 1,
  "options": [
    {
      "method": "api_token",
      "description": "Use an API token from your dashboard",
      "header": "Authorization: Bearer YOUR_API_KEY",
      "cost": "1 Cred Units",
      "signup_url": "https://app.credprotocol.com/account/register"
    },
    {
      "method": "x402_payment",
      "description": "Pay per request with USDC (no account required)",
      "header": "X-PAYMENT: <signed_payment>",
      "price": "$0.01",
      "currency": "USDC",
      "network": "base",
      "pay_to": "0x..."
    }
  ]
}
```

The response includes an `X-PAYMENT-REQUIRED` header with base64-encoded payment requirements that x402-compatible wallets can process automatically.

### Pricing

x402 payments use the same pricing as Cred Units at **\$0.01 per Cred Unit**:

| Operation       | Cred Units | x402 Price |
| --------------- | ---------- | ---------- |
| Credit Score    | 1 CU       | \$0.01     |
| Full Report     | 7 CUs      | \$0.07     |
| Enhanced Report | 10 CUs     | \$0.10     |

### Supported Networks

| Network            | Chain ID   | Type    | USDC Token                  |
| ------------------ | ---------- | ------- | --------------------------- |
| Base               | 8453       | Mainnet | USD Coin                    |
| Base Sepolia       | 84532      | Testnet | USD Coin                    |
| SKALE Base         | 1187947933 | Mainnet | Bridged USDC (SKALE Bridge) |
| SKALE Base Sepolia | 324705682  | Testnet | Bridged USDC (SKALE Bridge) |

<Tip>
  SKALE offers zero-gas transactions with sub-second finality, making it ideal for high-frequency micropayments.
</Tip>

### Integration

For detailed integration instructions, see the [x402 documentation](https://docs.cdp.coinbase.com/x402/welcome) from Coinbase Developer Platform.

<CodeGroup>
  ```javascript JavaScript (x402 SDK) theme={null}
  import { x402Client } from 'x402';

  const client = new x402Client({
    wallet: yourWallet,
    network: 'base'
  });

  // The client automatically handles 402 responses
  const response = await client.fetch('https://api.credprotocol.com/api/v2/score/address/vitalik.eth');
  const data = await response.json();
  ```

  ```python Python (Manual) theme={null}
  import requests
  import base64

  # First request - will get 402
  response = requests.get('https://api.credprotocol.com/api/v2/score/address/vitalik.eth')

  if response.status_code == 402:
      # Parse payment requirements from header
      payment_required = response.headers.get('X-PAYMENT-REQUIRED')
      requirements = base64.b64decode(payment_required)

      # Sign payment with your wallet (implementation depends on your wallet)
      signed_payment = sign_usdc_transfer(requirements)

      # Retry with payment
      response = requests.get(
          'https://api.credprotocol.com/api/v2/score/address/vitalik.eth',
          headers={'X-PAYMENT': signed_payment}
      )
  ```
</CodeGroup>
