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

# Authentication

> Learn how to authenticate your API requests with Day Copilot

## Overview

All DayCopilot API requests require authentication using **JSON Web Tokens (JWT)**. The API uses Bearer token authentication in the Authorization header.

## Getting Your Token

### Via Dashboard

1. Sign in to [DayCopilot](https://app.daycopilot.ai)
2. Navigate to your account settings
3. Generate an API token
4. Copy the JWT token for use in API requests

### Via OAuth 2.0 (Recommended for integrations)

For third-party integrations and applications, use OAuth 2.0:

```bash theme={null}
# Step 1: Redirect users to authorization endpoint
https://app.daycopilot.ai/api/oauth/authorize?
  client_id=YOUR_CLIENT_ID&
  response_type=code&
  redirect_uri=YOUR_REDIRECT_URI&
  scope=tasks:read tasks:write events:read events:write

# Step 2: Exchange authorization code for access token
curl -X POST "https://app.daycopilot.ai/api/oauth/token" \
  -H "Content-Type: application/x-www-form-urlencoded" \
  -d "grant_type=authorization_code" \
  -d "code=AUTHORIZATION_CODE" \
  -d "client_id=YOUR_CLIENT_ID" \
  -d "client_secret=YOUR_CLIENT_SECRET" \
  -d "redirect_uri=YOUR_REDIRECT_URI"
```

Response:

```json theme={null}
{
  "access_token": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...",
  "token_type": "Bearer",
  "expires_in": 3600,
  "refresh_token": "v1.MRqKkv...",
  "scope": "tasks:read tasks:write events:read events:write"
}
```

## Making Authenticated Requests

Include the JWT token in the `Authorization` header with the `Bearer` scheme:

<CodeGroup>
  ```bash cURL theme={null}
  curl -X GET "https://app.daycopilot.ai/api/v1/tasks" \
    -H "Authorization: Bearer YOUR_JWT_TOKEN"
  ```

  ```javascript JavaScript theme={null}
  const response = await fetch('https://app.daycopilot.ai/api/v1/tasks', {
    headers: {
      'Authorization': `Bearer ${token}`
    }
  });
  ```

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

  headers = {
      'Authorization': f'Bearer {token}'
  }
  response = requests.get('https://app.daycopilot.ai/api/v1/tasks', headers=headers)
  ```
</CodeGroup>

## Token Security Best Practices

<AccordionGroup>
  <Accordion title="Store Tokens Securely">
    * Never commit tokens to version control
    * Use environment variables or secure key management systems
    * Rotate tokens regularly (at least every 90 days)
    * Never expose tokens in client-side code or URLs
  </Accordion>

  <Accordion title="Handle Token Expiration">
    JWT tokens expire after a set period. Implement token refresh logic:

    ```javascript theme={null}
    async function refreshToken(refreshToken) {
      const response = await fetch('https://app.daycopilot.ai/api/oauth/token', {
        method: 'POST',
        headers: {
          'Content-Type': 'application/x-www-form-urlencoded'
        },
        body: new URLSearchParams({
          grant_type: 'refresh_token',
          refresh_token: refreshToken
        })
      });

      const { access_token } = await response.json();
      return access_token;
    }
    ```
  </Accordion>

  <Accordion title="Use HTTPS Only">
    Always use HTTPS when making API requests. Never send tokens over unencrypted HTTP connections.
  </Accordion>

  <Accordion title="Implement Token Revocation">
    If a token is compromised, revoke it immediately:

    ```bash theme={null}
    curl -X POST "https://app.daycopilot.ai/api/oauth/revoke" \
      -H "Content-Type: application/x-www-form-urlencoded" \
      -d "token=YOUR_ACCESS_TOKEN"
    ```
  </Accordion>
</AccordionGroup>

## OAuth 2.0 Scopes

DayCopilot supports fine-grained permissions via OAuth scopes:

| Scope            | Description                         |
| ---------------- | ----------------------------------- |
| `tasks:read`     | Read access to tasks                |
| `tasks:write`    | Create, update, and delete tasks    |
| `events:read`    | Read access to events               |
| `events:write`   | Create, update, and delete events   |
| `contexts:read`  | Read access to contexts             |
| `contexts:write` | Create, update, and delete contexts |
| `user:read`      | Read user profile information       |
| `user:write`     | Update user profile information     |

Request only the scopes your application needs:

```
scope=tasks:read tasks:write events:read
```

## Access Control

All API requests are automatically scoped to the authenticated user via access control policies:

* Users can only access their own data
* Users can access data explicitly shared with them
* Collaborative contexts respect sharing permissions
* All queries are filtered by user context

This means you don't need to manually filter by user ID - access control is handled automatically.

See [Access Control & Permissions](/concepts/access-control) for detailed information.

## Error Responses

### 401 Unauthorized

```json theme={null}
{
  "error": "Unauthorized",
  "message": "Missing or invalid authentication token",
  "status": 401
}
```

**Causes:**

* Missing `Authorization` header
* Invalid or expired token
* Malformed token

### 403 Forbidden

```json theme={null}
{
  "error": "Forbidden",
  "message": "Insufficient permissions to access this resource",
  "status": 403
}
```

**Causes:**

* Valid token but insufficient OAuth scopes
* Attempting to access another user's data
* Resource not shared with authenticated user

## Testing Authentication

Use this endpoint to verify your token is valid:

```bash theme={null}
curl -X GET "https://app.daycopilot.ai/api/oauth/userinfo" \
  -H "Authorization: Bearer YOUR_JWT_TOKEN"
```

Response:

```json theme={null}
{
  "id": "550e8400-e29b-41d4-a716-446655440000",
  "email": "user@example.com",
  "name": "John Doe",
  "created_at": "2025-01-15T10:00:00Z"
}
```

## Next Steps

<CardGroup cols={2}>
  <Card title="Quick Start" icon="rocket" href="/quickstart">
    Make your first authenticated API call
  </Card>

  <Card title="API Reference" icon="code" href="/api-reference/introduction">
    Explore authenticated endpoints
  </Card>
</CardGroup>
