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

# Authentication

> Learn about the two authentication methods for the Profy API — API Key and OAuth Bearer

The Profy Platform API supports two authentication methods, each suited to different integration scenarios. All authentication information is passed via the `Authorization` request header.

## API Key Authentication

API Key is the simplest authentication method, ideal for server-to-server direct calls.

### Usage

Add `Authorization: Bearer sk-pro-xxxx` to the request header:

<CodeGroup>
  ```python Python theme={null}
  from profy import Profy

  client = Profy(api_key="sk-pro-your-key-here")
  ```

  ```typescript TypeScript theme={null}
  import { Profy } from "@profy-ai/sdk";

  const client = new Profy({ apiKey: "sk-pro-your-key-here" });
  ```

  ```bash curl theme={null}
  curl -H "Authorization: Bearer sk-pro-your-key-here" \
       https://api.profy.cn/v1/models
  ```
</CodeGroup>

### Characteristics

| Property                | Description                                              |
| ----------------------- | -------------------------------------------------------- |
| **Prefix**              | `sk-pro-`                                                |
| **Credit Deduction**    | Deducted from the developer's own account                |
| **Supported Endpoints** | `/v1/agents/run`, `/v1/chat/completions`, `/v1/models`   |
| **Not Supported**       | `/v1/events` (requires OAuth)                            |
| **Storage**             | Stored as SHA-256 hash; plaintext shown only at creation |

### Use Cases

* Backend services calling AI capabilities
* Automation scripts and scheduled tasks
* Internal tools and management systems
* Development and testing

### Security Best Practices

<Warning>
  An API Key is a credential for your account. A leak could result in credit consumption. Follow these security practices:
</Warning>

1. **Do not use API Keys in frontend code** — browser-side code is visible to users
2. **Use environment variables** to store keys; do not hardcode them in source code
3. **Set expiration times** — choose an expiration period when creating the key in the Platform Console
4. **Assign scopes as needed** — do not use full permissions
5. **Rotate regularly** — periodically create new keys and revoke old ones

```bash theme={null}
# Recommended: Use environment variables
export PROFY_API_KEY="sk-pro-your-key-here"
```

<CodeGroup>
  ```python Python theme={null}
  import os
  from profy import Profy

  client = Profy(api_key=os.environ["PROFY_API_KEY"])
  ```

  ```typescript TypeScript theme={null}
  import { Profy } from "@profy-ai/sdk";

  const client = new Profy({
    apiKey: process.env.PROFY_API_KEY!,
  });
  ```
</CodeGroup>

## OAuth Bearer Authentication

OAuth authentication is suited for App scenarios that operate on behalf of users. Obtain an Access Token through the standard OAuth 2.0 Authorization Code flow.

### Usage

```bash theme={null}
curl -H "Authorization: Bearer eyJhbGciOiJSUzI1NiIs..." \
     https://api.profy.cn/v1/chat/completions
```

### Characteristics

| Property                   | Description                                      |
| -------------------------- | ------------------------------------------------ |
| **Token Format**           | JWT (RS256 signed)                               |
| **Credit Deduction**       | Deducted from the **authorizing user's** account |
| **Supported Endpoints**    | All `/v1/*` endpoints                            |
| **Access Token Validity**  | 1 hour                                           |
| **Refresh Token Validity** | 90 days (rotation mechanism)                     |

### Use Cases

* Apps calling AI models on behalf of users
* Third-party applications requiring user authorization
* SaaS products with per-user billing
* Custom billing event reporting (`/v1/events` supports OAuth only)

### OAuth Flow Overview

```
User → Your App → Profy Auth Page → User Consents → Auth Code → Exchange for Token
```

For the detailed OAuth integration guide, see [OAuth Integration](/en/developers/oauth-integration).

## Comparison

| Dimension            | API Key                        | OAuth Bearer                            |
| -------------------- | ------------------------------ | --------------------------------------- |
| **Complexity**       | Simple (just one key)          | More complex (requires full OAuth flow) |
| **Credit Source**    | Developer's account            | Authorizing user's account              |
| **Use Case**         | Server-side direct calls       | Apps acting on behalf of users          |
| **Events API**       | ❌ Not supported                | ✅ Supported                             |
| **Token Management** | Manual creation and revocation | Automatic expiration and refresh        |
| **Frontend Safe**    | ❌ Not secure                   | ✅ Safe (short-lived tokens)             |

### How to Choose

<Steps>
  <Step title="Determine the billing subject">
    If credits should be deducted from **your own account** → API Key

    If credits should be deducted from **the user's account** → OAuth
  </Step>

  <Step title="Determine the calling pattern">
    If it's a **backend service** calling directly → API Key

    If it's an **App acting on behalf of a user** → OAuth
  </Step>

  <Step title="Determine feature requirements">
    If you need to use the **Events API** to report custom billing events → OAuth

    For other scenarios, either method works
  </Step>
</Steps>

## Authentication Errors

When authentication fails, the API returns the following errors:

| HTTP Status | Scenario                   | Description                                                 |
| ----------- | -------------------------- | ----------------------------------------------------------- |
| `401`       | API Key invalid or expired | Check if the key is correct, revoked, or expired            |
| `401`       | Access Token expired       | Use the Refresh Token to obtain a new Access Token          |
| `401`       | Refresh Token invalid      | User needs to re-authorize                                  |
| `403`       | Insufficient permissions   | The API Key's scope does not include the requested endpoint |

Error response example:

```json theme={null}
{
  "error": {
    "message": "Unauthorized",
    "type": "auth_error"
  }
}
```

## Rate Limits

API calls are protected by rate limits. Limits are calculated per API Key or per user associated with the OAuth Token.

When a rate limit is triggered, the API returns `429 Too Many Requests`:

```json theme={null}
{
  "error": {
    "message": "Rate limit exceeded",
    "type": "rate_limit_error"
  }
}
```

<Tip>
  You can view your API call volume and rate usage on the Usage Stats page of the [Platform Console](https://platform.profy.cn).
</Tip>

## Next Steps

<CardGroup cols={2}>
  <Card title="API Key Management" icon="key" href="/en/developers/api-key-management">
    Complete guide to creating, viewing, and revoking API Keys
  </Card>

  <Card title="OAuth Integration" icon="shield" href="/en/developers/oauth-integration">
    Complete OAuth 2.0 integration flow
  </Card>
</CardGroup>
