> For clean Markdown of any page, append .md to the page URL.
> For a complete documentation index, see https://docs.governanceaicore.com/llms.txt.
> For AI client integration (Claude Code, Cursor, etc.), connect to the MCP server at https://docs.governanceaicore.com/_mcp/server.

# Authentication & API Keys

> Secure access to GovernanceAI APIs with authentication methods and key management

# Authentication & API Keys

GovernanceAI uses industry-standard authentication methods to secure API access. This guide covers all authentication options.

## Authentication Methods

GovernanceAI supports multiple authentication methods depending on which APIs you're accessing:

### 1. Session-Based Authentication (Control Plane)

Used for dashboard access and Control Plane configuration APIs.

**Flow:**

* User logs in via OAuth (Google, GitHub, Microsoft, Okta, etc.)
* Server creates a secure session
* Session cookie (`governance_session`) is set in browser
* Subsequent requests include the session cookie automatically

**Security Features:**

* HttpOnly flag prevents JavaScript access
* Secure flag requires HTTPS
* SameSite=Lax prevents CSRF attacks
* Session timeout after 24 hours of inactivity
* Token rotation on sensitive operations

### 2. Bearer Token Authentication (Runtime & APIs)

Used for API calls from your application to GovernanceAI Runtime.

**Bearer Token Format:**

```
Authorization: Bearer gak_prod_1234567890abcdefghijklmnopqr
```

**Token Structure:**

* Prefix: `gak_` (GovernanceAI API Key)
* Environment: `prod` (production) or `dev` (development)
* Key ID and secret (unique per key)

**Advantages:**

* Stateless authentication
* No session management needed
* Ideal for microservices and CI/CD
* Can have different expiration policies
* Easy to rotate and revoke

### 3. Alternative Headers

For compatibility with certain frameworks or proxies:

```bash
# Option A: X-API-Key header
curl -H "X-API-Key: gak_prod_1234567890abcdefghijklmnopqr" \
  https://api.governanceai.com/v1/guardrails/evaluate

# Option B: X-App-API-Key header
curl -H "X-App-API-Key: gak_prod_1234567890abcdefghijklmnopqr" \
  https://api.governanceai.com/v1/guardrails/evaluate

# Option C: Custom header (if configured)
curl -H "X-Custom-Key: gak_prod_1234567890abcdefghijklmnopqr" \
  https://api.governanceai.com/v1/guardrails/evaluate
```

### 4. Pipeline Token Authentication

For CI/CD pipelines and automated scanning.

**Use Case:** GitHub Actions, GitLab CI, Jenkins scanning for compliance violations.

**Token Format:**

```
X-Pipeline-Token: gpt_prod_1234567890abcdefghijklmnopqr
```

**Permissions:**

* Limited to specific operations (usually read-only)
* Tied to specific pipeline/workflow
* Cannot manage policies or settings
* High-frequency rate limits

## Generating API Keys

### Step-by-Step Guide

#### 1. Access API Keys Page

**SaaS:**

* Log in to dashboard at `https://app.governanceai.com`
* Click your avatar (top right) → **Settings**
* Navigate to **API Keys**

**On-Premise:**

* Log in to your instance
* Click your avatar → **Settings**
* Navigate to **API Keys**

#### 2. Create New Key

* Click **Create New API Key**

* Fill in the form:
  * **Name:** `Production Runtime` (descriptive name for your reference)
  * **Environment:** Select `Production` or `Development`
  * **Scope:** Choose what this key can do:
    * `runtime:execute` - Call runtime guardrails APIs
    * `runtime:read` - Query guardrail results
    * `control:admin` - Full control plane access
    * `scans:read` - Read scan results
    * Custom scopes for granular control
  * **Expiration:** Set expiration date (or never expire)
  * **Rate Limit:** Set requests per minute (optional)

* Click **Generate Key**

#### 3. Secure the Key

⚠️ **Important:** You will only see the full key once. Copy and store it securely.

```bash
# Option 1: Environment variable
export GOVERNANCEAI_API_KEY="gak_prod_1234567890abcdefghijklmnopqr"

# Option 2: .env file (never commit to git!)
echo "GOVERNANCEAI_API_KEY=gak_prod_1234567890abcdefghijklmnopqr" >> .env

# Option 3: Secrets management
# Use AWS Secrets Manager, HashiCorp Vault, or similar
```

### Key Rotation

**Manual Rotation:**

* Go to **Settings** → **API Keys**
* Find the key you want to rotate
* Click **Rotate Key**
* Confirm the action
* Old key becomes inactive after 24 hours
* Update your applications to use the new key
* Verify new key is working
* Deactivate the old key

**Automatic Rotation (Enterprise):**

Contact support to enable automatic key rotation with custom schedules.

## Using API Keys

### cURL Example

```bash
# Simple GET request
curl -H "Authorization: Bearer gak_prod_1234567890abcdefghijklmnopqr" \
  https://api.governanceai.com/v1/org

# With request body
curl -X POST \
  -H "Authorization: Bearer gak_prod_1234567890abcdefghijklmnopqr" \
  -H "Content-Type: application/json" \
  -d '{"policy": "block_unsafe_content"}' \
  https://api.governanceai.com/v1/guardrails/evaluate
```

### Python Example

```python
import requests

api_key = "gak_prod_1234567890abcdefghijklmnopqr"
headers = {
    "Authorization": f"Bearer {api_key}",
    "Content-Type": "application/json"
}

response = requests.post(
    "https://api.governanceai.com/v1/guardrails/evaluate",
    headers=headers,
    json={
        "messages": [{"role": "user", "content": "Hello"}],
        "context": {"org_id": "org_123"}
    }
)

print(response.json())
```

### Node.js Example

```javascript
const axios = require('axios');

const apiKey = process.env.GOVERNANCEAI_API_KEY;
const client = axios.create({
  baseURL: 'https://api.governanceai.com/v1',
  headers: {
    'Authorization': `Bearer ${apiKey}`,
    'Content-Type': 'application/json'
  }
});

const response = await client.post('/guardrails/evaluate', {
  messages: [{ role: 'user', content: 'Hello' }],
  context: { org_id: 'org_123' }
});

console.log(response.data);
```

## Token Expiration & Refresh

### SaaS Tokens

* **Default Expiration:** 90 days
* **Configurable:** Up to 2 years
* **Automatic Renewal:** On use, extends by original duration
* **Revocation:** Immediate invalidation on key rotation

### On-Premise Tokens

Configure token lifetime in your deployment:

```yaml
# In values.yaml or config
auth:
  token_lifetime: 86400 # 24 hours in seconds
  refresh_token_lifetime: 604800 # 7 days
  allow_auto_renewal: true
```

## Security Best Practices

### Do's ✅

* **Store securely:** Use environment variables, secrets managers, or .env files
* **Limit scope:** Use minimal required permissions
* **Rotate regularly:** Rotate keys every 90 days
* **Monitor usage:** Check audit logs for unusual activity
* **Use different keys:** One key per environment/application
* **Set expiration:** Keys should expire if not renewed
* **Use HTTPS:** Always use encrypted connections

### Don'ts ❌

* **Commit to git:** Never include keys in source code
* **Share keys:** One key per person/service
* **Use in URLs:** Keys in query parameters are logged
* **Long lifespans:** Avoid keys that never expire
* **Reuse across environments:** Don't use prod key in dev
* **Log keys:** Never print or log API keys
* **Use broad scopes:** Only request needed permissions

## Revoking Keys

### Emergency Revocation

If a key is compromised:

* Go to **Settings** → **API Keys**
* Find the compromised key
* Click **⋯ (More)** → **Revoke Immediately**
* Confirm the action
* The key becomes invalid instantly
* Check audit logs for unauthorized usage

### Audit Trail

All key operations are logged:

```bash
# View API key activity
curl -H "Authorization: Bearer $API_KEY" \
  https://api.governanceai.com/v1/audit/logs?resource_type=api_key
```

## Troubleshooting

### 401 Unauthorized

**Cause:** Invalid or missing API key

**Solution:**

* Verify API key format (should start with `gak_`)
* Check Authorization header: `Authorization: Bearer <key>`
* Ensure key hasn't been rotated
* Verify key scope includes the operation

### 403 Forbidden

**Cause:** Key doesn't have permission for this operation

**Solution:**

* Check key scopes in **Settings** → **API Keys**
* Create a new key with appropriate scopes
* Verify organization and workspace access

### 429 Too Many Requests

**Cause:** Rate limit exceeded

**Solution:**

* Check rate limit in key details
* Implement exponential backoff
* Contact support to increase rate limits

## Next Steps

* **[Quick Start Guide](./05-quick-start.mdx)** - Make your first API call
* **[Code Examples](/code-examples/curl-examples)** - See authentication in action
* **[API Reference](/api)** - Full endpoint documentation