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

# Civic Tokens

> Learn how to use Civic tokens for authentication with third-party services and custom applications

# Civic Tokens

Civic tokens provide a way to authenticate with Civic from services that don't support browser-based OAuth flows, such as OpenAI Agent Builder, workflow automation platforms, and custom applications.

<Note>
  **Most users don't need tokens** - If you're using Claude Desktop, VS Code, Cursor, or other MCP-compatible desktop agents, use [browser authentication](/civic/quickstart) instead. Tokens are only needed for specific use cases described below.
</Note>

## What are Civic Tokens?

Civic tokens are temporary access tokens that grant permission to use your Civic MCP servers from external services. They are:

* **Profile-scoped**: Each token is tied to a specific Civic profile (toolkit)
* **Time-limited**: Tokens expire after a configurable period (up to 30 days)
* **Delegated**: Tokens are delegated credentials that allow external services to act on your behalf
* **Secure**: Tokens use industry-standard OAuth 2.0 token exchange (RFC 8693)

<Note>
  **What is a delegated token?** A delegated token allows an external service or application to access your Civic resources on your behalf. The service acts with the same permissions you have, but the token is scoped to a specific profile (toolkit) to limit what resources can be accessed.
</Note>

## When to Use Tokens vs Browser Auth

### Use Browser Authentication

Browser authentication works well for interactive use cases:

<CardGroup cols={2}>
  <Card title="Desktop AI Agents" icon="desktop">
    Claude Desktop, Cursor, VS Code - authenticate through your browser
  </Card>

  <Card title="Interactive Sessions" icon="user">
    Any client where you can complete an OAuth flow in your browser
  </Card>
</CardGroup>

### Use Token Authentication

Generate a token when you need to:

<CardGroup cols={2}>
  <Card title="Agent Builders" icon="robot">
    **OpenAI Agent Builder** - Requires token upfront for authentication
  </Card>

  <Card title="Automation Platforms" icon="workflow">
    **n8n** and similar workflow tools that run server-side
  </Card>

  <Card title="Custom Applications" icon="code">
    **Server-to-server integrations** - Your own apps and services
  </Card>

  <Card title="Restricted Environments" icon="lock">
    **CI/CD, scripts** - Where browser OAuth isn't available
  </Card>
</CardGroup>

**Why these services need tokens:**

Tokens are appropriate for background processes such as autonomous agents, scheduled tasks, or other unattended workflows. These services:

* Run server-side without browser access for OAuth flows
* Require credentials configured ahead of time
* Can't trigger interactive authentication during execution
* Need persistent authentication for automated operations

## How to Generate a Token

<Steps>
  <Step title="Navigate to Install page">
    Go to [app.civic.com](https://app.civic.com) and click on the **Tools** menu, then select **Install**
  </Step>

  <Step title="Select your toolkit">
    Choose the profile (toolkit) you want to generate a token for. When you change the toolkit, the MCP URL will automatically update.
  </Step>

  <Step title="Click Install">
    Click the **Install** button to generate your token
  </Step>

  <Step title="Set token expiration">
    Choose how long the token should be valid (up to 30 days). The expiration date will be displayed based on your selection.
  </Step>

  <Step title="Copy and store securely">
    After generating, copy the token immediately and store it securely

    <Warning>
      **Token displayed only once** - The token is only shown once. If you lose it, you'll need to generate a new one.
    </Warning>
  </Step>
</Steps>

## Using Tokens in Different Services

### OpenAI Agent Builder

When setting up an OpenAI agent that needs to access your Civic tools:

<Steps>
  <Step title="Create your agent">
    In OpenAI Agent Builder, create a new agent or edit an existing one
  </Step>

  <Step title="Add MCP server">
    Under **Tools & Integrations**, add a new MCP server connection
  </Step>

  <Step title="Configure the connection">
    ```
    MCP URL: https://app.civic.com/hub/mcp?accountId=YOUR_ACCOUNT_ID&profile=YOUR_PROFILE_NAME
    Authentication: Bearer token
    Token: YOUR_CIVIC_TOKEN_HERE
    ```
  </Step>

  <Step title="Test the connection">
    Save and test that your agent can access the Civic tools
  </Step>
</Steps>

<Tip>
  **URL parameters**:

  * `accountId` - Your Civic account ID
  * `profile` - The profile name (toolkit) that determines which MCP servers the agent can access
  * `lock` - Whether to lock the session to the specified profile (`true` by default when a profile is set, `false` to allow profile switching)
  * `skills` - Comma-separated list of skill aliases to load into the session

  Use the profile alias you created in Civic.
</Tip>

### n8n Workflows

To use Civic in your n8n automations:

<Steps>
  <Step title="Add HTTP Request node">
    In your n8n workflow, add an **HTTP Request** node
  </Step>

  <Step title="Configure authentication">
    ```
    URL: https://app.civic.com/hub/mcp?accountId=YOUR_ACCOUNT_ID&profile=YOUR_PROFILE_NAME
    Authentication: Header Auth
    Header Name: Authorization
    Header Value: Bearer YOUR_CIVIC_TOKEN_HERE
    ```
  </Step>

  <Step title="Set up MCP request">
    Configure your MCP tool calls in the request body following the [MCP protocol specification](https://spec.modelcontextprotocol.io/)
  </Step>
</Steps>

### Other Automation Platforms

Similar to n8n, other workflow automation platforms can use Civic tokens with HTTP modules and Bearer token authentication. The general pattern is:

```
URL: https://app.civic.com/hub/mcp?accountId=YOUR_ACCOUNT_ID&profile=YOUR_PROFILE_NAME
Authentication: Header Auth or Bearer Token
Header Name: Authorization
Header Value: Bearer YOUR_CIVIC_TOKEN_HERE
Content-Type: application/json
```

### Custom Applications

Include the token in the Authorization header of your HTTP requests:

<Tabs>
  <Tab title="cURL">
    ```bash theme={null}
    curl 'https://app.civic.com/hub/mcp?accountId=YOUR_ACCOUNT_ID&profile=my-profile' \
      -H "Authorization: Bearer YOUR_TOKEN_HERE" \
      -H "Content-Type: application/json" \
      -d '{
        "jsonrpc": "2.0",
        "id": 1,
        "method": "tools/list"
      }'
    ```
  </Tab>

  <Tab title="JavaScript">
    ```javascript theme={null}
    const response = await fetch('https://app.civic.com/hub/mcp?accountId=YOUR_ACCOUNT_ID&profile=my-profile', {
      method: 'POST',
      headers: {
        'Authorization': `Bearer ${process.env.CIVIC_TOKEN}`,
        'Content-Type': 'application/json',
      },
      body: JSON.stringify({
        jsonrpc: '2.0',
        id: 1,
        method: 'tools/list'
      })
    });

    const data = await response.json();
    console.log(data);
    ```
  </Tab>

  <Tab title="Python">
    ```python theme={null}
    import requests
    import os

    headers = {
        'Authorization': f'Bearer {os.environ.get("CIVIC_TOKEN")}',
        'Content-Type': 'application/json'
    }

    payload = {
        'jsonrpc': '2.0',
        'id': 1,
        'method': 'tools/list'
    }

    response = requests.post(
        'https://app.civic.com/hub/mcp?accountId=YOUR_ACCOUNT_ID&profile=my-profile',
        headers=headers,
        json=payload
    )

    print(response.json())
    ```
  </Tab>
</Tabs>

## Credential Access with Tokens

Civic tokens always result in a **locked profile**. This means the token can only access credentials that have been explicitly [assigned to the profile](/civic/reference/authorizations#profile-assignment). Unassigned credentials — even ones that would otherwise match — are not available.

<Warning>
  **If you are rolling out token-based access for an existing profile**, credentials that were previously resolved automatically (because the profile was unlocked) may now require explicit assignment. Check the authorizations dashboard to ensure your profile has the credentials it needs before switching to token authentication.
</Warning>

New credentials authenticated through a token session are automatically assigned to the token's profile.

## Token Expiration & Renewal

### Expiration

* You can configure token expiration up to a maximum of 30 days
* Expired tokens return a `401 Unauthorized` error
* You'll receive no warning before expiration
* The expiration date is shown when you generate the token

### Renewal

Tokens cannot be renewed. To continue access after expiration:

<Steps>
  <Step title="Generate a new token">
    Follow the [token generation steps](#how-to-generate-a-token) above
  </Step>

  <Step title="Update your service">
    Replace the old token with the new one in your service/application
  </Step>

  <Step title="Old token invalidated">
    The expired token is automatically invalidated
  </Step>
</Steps>

<Tip>
  **Best Practice**: Set calendar reminders a few days before token expiration to avoid service interruption. Consider using shorter expiration periods for better security.
</Tip>

## Security Best Practices

### Storage

<AccordionGroup>
  <Accordion title="Never commit tokens to version control" icon="git-alt">
    **Bad ❌**

    ```javascript theme={null}
    const token = 'eyJhbGciOiJSUzI1NiIsInR5cCI6IkpXVCJ9...';
    ```

    **Good ✅**

    ```javascript theme={null}
    const token = process.env.CIVIC_TOKEN;
    ```

    Always use environment variables and add `.env` to your `.gitignore`:

    ```bash theme={null}
    # .env (add to .gitignore!)
    CIVIC_TOKEN=your_token_here
    ```
  </Accordion>

  <Accordion title="Use secret management services" icon="vault">
    For production environments, use dedicated secret managers:

    * **AWS Secrets Manager** - For AWS deployments
    * **HashiCorp Vault** - For multi-cloud or on-premises
    * **Google Secret Manager** - For GCP deployments
    * **Azure Key Vault** - For Azure deployments
  </Accordion>

  <Accordion title="Rotate tokens regularly" icon="rotate">
    * Generate new tokens before old ones expire
    * Don't wait until the last day
    * Update services with new tokens proactively
    * Test that the new token works before the old one expires
  </Accordion>

  <Accordion title="Rotate tokens before expiration" icon="clock">
    * Tokens can be configured for up to 30 days
    * Set reminders to rotate tokens before they expire
    * Generate new tokens proactively to avoid service interruption
    * Use shorter expiration periods for better security
    * Consider your organization's security policies and compliance requirements
  </Accordion>
</AccordionGroup>

### Access Control

<CardGroup cols={2}>
  <Card title="One token per service" icon="key">
    Generate separate tokens for different services to isolate potential breaches
  </Card>

  <Card title="Use appropriate profiles" icon="toolbox">
    Create dedicated profiles for specific use cases with only necessary tools
  </Card>

  <Card title="Use shorter expiration periods" icon="clock">
    Configure tokens with shorter lifetimes when possible for better security
  </Card>

  <Card title="Monitor token usage" icon="chart-line">
    Check the Activity page for unexpected usage patterns
  </Card>
</CardGroup>

## Troubleshooting

<AccordionGroup>
  <Accordion title="401 Unauthorized" icon="lock">
    **Cause**: Token is expired, invalid, or incorrectly formatted

    **Solutions**:

    * Verify token is correctly copied (no extra spaces or line breaks)
    * Check token hasn't expired
    * Generate a new token if needed
    * Ensure Authorization header format: `Bearer YOUR_TOKEN` (note the space after "Bearer")
    * Verify you're using the correct profile parameter in the URL
  </Accordion>

  <Accordion title="403 Forbidden" icon="ban">
    **Cause**: Token doesn't have access to the requested profile or resources

    **Solutions**:

    * Verify the token was generated for the correct profile
    * Check that the profile name in the MCP URL matches the token's profile
    * Ensure the profile has access to the MCP servers you're trying to use
    * Confirm the profile exists and is active in your Civic account
  </Accordion>

  <Accordion title="Token not working in automation platform" icon="robot">
    **Cause**: Incorrect header format or URL configuration

    **Solutions**:

    * Double-check the Authorization header: `Authorization: Bearer YOUR_TOKEN`
    * Verify the MCP URL includes both accountId and profile parameters
    * Ensure Content-Type header is set: `Content-Type: application/json`
    * Test the token with a simple curl command first to isolate the issue
  </Accordion>

  <Accordion title="How do I know when my token expires?" icon="calendar">
    **Answer**: The expiration date is shown when you generate the token

    **Solutions**:

    * Set a calendar reminder when you generate the token
    * Note the expiration date in your documentation
    * Implement monitoring in your application to detect 401 errors
    * Use shorter expiration periods for sensitive integrations
  </Accordion>
</AccordionGroup>

## Comparison: Browser Auth vs Token Auth

| Feature              | Browser Authentication                    | Token Authentication                                     |
| -------------------- | ----------------------------------------- | -------------------------------------------------------- |
| **Best for**         | Desktop AI agents, interactive sessions   | Background processes, autonomous agents, scheduled tasks |
| **Setup**            | Click connect → browser opens → authorize | Generate token → copy to service                         |
| **Token management** | Automatic refresh                         | Manual generation (configurable up to 30 days)           |
| **Use cases**        | Claude Desktop, VS Code, Cursor           | OpenAI Agent Builder, n8n, custom apps                   |
| **Security**         | OAuth flow, automatic refresh             | Manual rotation, environment variables                   |
| **Expiration**       | Auto-refreshed                            | Configurable (up to 30 days), no auto-renewal            |

## Next Steps

<CardGroup cols={2}>
  <Card title="Installing into an agent" icon="robot" href="/civic/quickstart/clients/agents">
    Learn about profile locking, skills, and other agent-specific configuration
  </Card>

  <Card title="Create your first toolkit" icon="toolbox" href="/civic/concepts/toolkits">
    Set up a toolkit to organize your MCP servers before generating tokens
  </Card>

  <Card title="Manage authorizations" icon="key" href="/civic/reference/authorizations">
    View your authorizations and connected services
  </Card>

  <Card title="OpenAI Agent setup" icon="robot" href="/civic/recipes/openai-agents">
    Complete guide to using Civic tokens with OpenAI Agent Builder
  </Card>
</CardGroup>
