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

# Authentication

> Learn how to authenticate with Monei infrastructure and secure your API requests

## Overview

Monei supports api key authentication method

## API Key Authentication

The simplest and most common authentication method for server-side applications.

### Getting Your API Key

<Steps>
  <Step title="Navigate to Dashboard">
    Go to [monei.cc](https://monei.cc/api-keys)
  </Step>

  <Step title="Create New Key">
    Click **Create New Key** and provide:

    * Key name (for identification)
    * Environment (sandbox or production)
    * Permissions (optional scoping)
  </Step>

  <Step title="Save Securely">
    Copy your API key immediately - it won't be shown again

    <Warning>
      Store API keys in environment variables, never commit them to source control.
    </Warning>
  </Step>
</Steps>

### Using API Keys

Include your API key in the `x-api-key` header:

<CodeGroup>
  ```javascript Node.js theme={null}
  import MoneiSDK from 'monei-sdk';

  const monei = new MoneiSDK({
    apiKey: process.env.MONEI_API_KEY,
  });

  // All requests will include the API key automatically
  const account = await monei.user.getWallet();
  ```

  ```python Python theme={null}
  from monei import MoneiClient
  import os

  monei = MoneiClient(
      api_key=os.getenv('MONEI_API_KEY')
  )

  # All requests will include the API key
  account = monei.user.get_wallet()
  ```

  ```bash cURL theme={null}
  curl https://api.monei.cc/api/v1/user/me \
    -H "x-api-key: YOUR_API_KEY"
  ```
</CodeGroup>

### API Key Permissions

Control what your API keys can access:

| Permission             | Description                       | Use Case             |
| ---------------------- | --------------------------------- | -------------------- |
| **Read Only**          | View account and transaction data | Analytics dashboards |
| **Transactions**       | Execute transactions              | Payment processing   |
| **Account Management** | Modify account settings           | Admin operations     |
| **Full Access**        | All operations                    | Backend services     |

<Info>
  Always use the minimum required permissions for each API key to enhance security.
</Info>

***

## Security Best Practices

<AccordionGroup>
  <Accordion icon="shield-check" title="API Key Management">
    **Do:**

    * Store keys in environment variables
    * Use different keys for development and production
    * Rotate keys regularly (every 90 days)
    * Use scoped permissions
    * Monitor key usage

    **Don't:**

    * Commit keys to version control
    * Share keys via email or chat
    * Use production keys in development
    * Hardcode keys in client-side code
  </Accordion>

  <Accordion icon="lock" title="Token Security">
    **Storage:**

    * Server-side: Environment variables, secure vaults
    * Client-side: httpOnly cookies, secure storage APIs
    * Never in localStorage or sessionStorage

    **Transmission:**

    * Always use HTTPS
    * Never include tokens in URLs
    * Use secure headers only

    **Lifecycle:**

    * Implement token refresh before expiration
    * Clear tokens on logout
    * Revoke compromised tokens immediately
  </Accordion>

  <Accordion icon="network-wired" title="Network Security">
    **Transport:**

    * Always use TLS 1.2 or higher
    * Verify SSL certificates
    * Use certificate pinning in mobile apps

    **Rate Limiting:**

    * Implement client-side rate limiting
    * Handle 429 responses gracefully
    * Use exponential backoff

    **IP Whitelisting:**

    * Restrict API access to known IPs (enterprise)
    * Use VPN for sensitive operations
  </Accordion>

  <Accordion icon="eye" title="Monitoring & Auditing">
    **Track:**

    * All authentication attempts
    * Failed login attempts
    * API key usage patterns
    * Unusual activity

    **Alerts:**

    * Multiple failed logins
    * API calls from new locations
    * Suspicious transaction patterns
    * Key usage spikes

    **Logging:**

    * Log all authentication events
    * Monitor access patterns
    * Review logs regularly
    * Set up automated alerts
  </Accordion>
</AccordionGroup>

***

## Authentication Errors

Common authentication errors and how to resolve them:

<Tabs>
  <Tab title="401 Unauthorized">
    **Cause:** Invalid or missing credentials

    **Solutions:**

    * Verify API key is correct
    * Check token hasn't expired
    * Ensure proper header format
    * Confirm environment (sandbox vs production)

    ```json theme={null}
    {
      "statusCode": 401,
      "message": "Invalid API key",
      "error": "Unauthorized"
    }
    ```
  </Tab>

  <Tab title="403 Forbidden">
    **Cause:** Valid credentials but insufficient permissions

    **Solutions:**

    * Check API key permissions
    * Verify account tier limits
    * Ensure operation is allowed
    * Contact support for permission changes

    ```json theme={null}
    {
      "statusCode": 403,
      "message": "Insufficient permissions",
      "error": "Forbidden"
    }
    ```
  </Tab>

  <Tab title="429 Rate Limited">
    **Cause:** Too many requests in a short period

    **Solutions:**

    * Implement exponential backoff
    * Check rate limit headers
    * Upgrade plan if needed
    * Cache responses when possible

    ```json theme={null}
    {
      "statusCode": 429,
      "message": "Rate limit exceeded",
      "retryAfter": 60
    }
    ```
  </Tab>
</Tabs>

***

## Environment Variables

Recommended environment variable structure:

<CodeGroup>
  ```bash .env theme={null}
  # Monei API Configuration
  MONEI_API_KEY=your_api_key_here
  ```

  ```javascript .env.example theme={null}
  # Copy this file to .env and fill in your values

  # Required
  MONEI_API_KEY=
  MONEI_ENVIRONMENT=sandbox

  ```
</CodeGroup>

<Warning>
  Never commit your `.env` file to version control. Add it to `.gitignore`.
</Warning>

***

## Testing Authentication

Test your authentication setup:

<CodeGroup>
  ```javascript test-auth.js theme={null}
  import MoneiSDK from 'monei-sdk';

  async function testAuthentication() {
    const monei = new MoneiSDK({
      apiKey: process.env.MONEI_API_KEY,
    });

    try {
      // Test API key authentication
      const account = await monei.user.getCurrentUser();
      console.log('✓ Authentication successful');
      console.log('Account ID:', account.id);
      console.log('KYC Tier:', account.kycInfo.currentTier);
      
      return true;
    } catch (error) {
      console.error('✗ Authentication failed:', error.message);
      return false;
    }
  }

  testAuthentication();
  ```

  ```python test_auth.py theme={null}
  from monei import MoneiClient
  import os

  def test_authentication():
      monei = MoneiClient(
          api_key=os.getenv('MONEI_API_KEY')
      )
      
      try:
          # Test API key authentication
          account = monei.user.get_current_user()
          print('✓ Authentication successful')
          print(f'Account ID: {account.id}')
          print(f'KYC Tier: {account.kyc_info.current_tier}')
          return True
      except Exception as error:
          print(f'✗ Authentication failed: {str(error)}')
          return False

  if __name__ == '__main__':
      test_authentication()
  ```

  ```bash test-auth.sh theme={null}
  #!/bin/bash

  # Test authentication
  RESPONSE=$(curl -s -w "\n%{http_code}" \
    https://api.monei.cc/api/v1/user/me \
    -H "x-api-key: $MONEI_API_KEY")

  HTTP_CODE=$(echo "$RESPONSE" | tail -n1)
  BODY=$(echo "$RESPONSE" | head -n-1)

  if [ "$HTTP_CODE" = "200" ]; then
    echo "✓ Authentication successful"
    echo "$BODY" | jq .
  else
    echo "✗ Authentication failed (HTTP $HTTP_CODE)"
    echo "$BODY" | jq .
  fi
  ```
</CodeGroup>

***

## Next Steps

<CardGroup cols={2}>
  <Card title="Core Concepts" icon="book" href="/core-concepts/wallets">
    Learn about wallets, transactions, and networks
  </Card>

  <Card title="Security Guidelines" icon="shield" href="/security/guidelines">
    Comprehensive security best practices
  </Card>

  <Card title="API Reference" icon="code" href="/api-reference/account">
    Explore all available endpoints
  </Card>

  <Card title="Webhooks" icon="webhook" href="/security/webhooks">
    Set up secure webhook integrations
  </Card>
</CardGroup>
