# Authentik OAuth Configuration

## Overview

Headquarter uses Authentik as its OAuth2 provider for authentication. This guide covers setting up Authentik and configuring Headquarter to work with it.

## Prerequisites

- Running Authentik instance
- Admin access to Authentik
- Headquarter deployed and accessible

## Authentik Setup

### Step 1: Create Application

1. Log in to Authentik Admin interface
2. Navigate to **Applications** → **Applications**
3. Click **Create**
4. Fill in:
   - **Name**: Headquarter
   - **Slug**: `headquarter-web` (or your preferred slug)
   - **Provider**: Create new

### Step 2: Create OAuth Provider

1. In the provider creation form:
   - **Name**: Headquarter OAuth
   - **Authentication flow**: `default-authentication-flow`
   - **Authorization flow**: `default-provider-authorization-explicit-consent`
   - **Client type**: Confidential
   - **Client ID**: Generate or use your own UUID
   - **Client Secret**: Generate strong secret
   - **Redirect URIs**: `https://api.yourdomain.com/auth/callback`

2. **Advanced protocol settings**:
   - **Signing Key**: Select a signing key (required)
   - **Access Token validity**: Minutes (default: 5)
   - **Refresh Token validity**: Days (default: 30)

3. Save provider

### Step 3: Configure Application

1. Return to Application configuration
2. Select the created provider
3. Save application

### Step 4: Verify URLs

Note these URLs from your Authentik instance:
- **Authorize URL**: `https://auth.yourdomain.com/application/o/authorize/`
- **Token URL**: `https://auth.yourdomain.com/application/o/token/`
- **UserInfo URL**: `https://auth.yourdomain.com/application/o/userinfo/`
- **JWKS URL**: `https://auth.yourdomain.com/application/o/headquarter-web/jwks/`

## Headquarter Configuration

### Environment Variables

Add to your `.env` file:

```bash
# Authentik Configuration
AUTHENTIK_DOMAIN=auth.yourdomain.com
AUTHENTIK_CLIENT_ID=your-client-id-uuid
AUTHENTIK_CLIENT_SECRET=your-generated-secret
AUTHENTIK_APPLICATION_SLUG=headquarter-web
AUTHENTIK_AUDIENCE=your-client-id-uuid

# Optional: Override default URLs if needed
# AUTHENTIK_AUTHORIZE_URL=https://auth.yourdomain.com/application/o/authorize/
# AUTHENTIK_TOKEN_URL=https://auth.yourdomain.com/application/o/token/
# AUTHENTIK_JWKS_URL=https://auth.yourdomain.com/application/o/headquarter-web/jwks/
# AUTHENTIK_ISSUER=https://auth.yourdomain.com/application/o/headquarter-web/
```

### Important Notes

- **AUTHENTIK_CLIENT_ID**: The UUID from Authentik (used for OAuth)
- **AUTHENTIK_APPLICATION_SLUG**: The URL-friendly name (e.g., `headquarter-web`)
- **AUTHENTIK_AUDIENCE**: Usually same as Client ID

## User Synchronization

On first login, Headquarter creates a local user record:

```python
user = User(
    email="user@example.com",
    name="User Name",
    authentik_id="authentik-user-id",
)
```

### Synced Fields

| Authentik Field | Headquarter Field |
|----------------|-------------------|
| email | email |
| name | name |
| sub (user ID) | authentik_id |
| groups | (future: team membership) |

## Troubleshooting

### Redirect URI Error

**Problem**: "Redirect URI Error" from Authentik

**Solution**:
1. Check redirect URI in Authentik matches exactly
2. Must include protocol: `https://api.yourdomain.com/auth/callback`
3. No trailing slash difference

### Invalid Client

**Problem**: "invalid_client" error

**Solution**:
1. Verify Client ID matches
2. Verify Client Secret is correct
3. Check application slug in URLs

### Missing Refresh Token

**Problem**: Authentik doesn't return refresh token

**Solution**:
This is normal. Headquarter creates its own session cookies and doesn't need refresh tokens from Authentik.

### CORS Errors

**Problem**: CORS errors in browser

**Solution**:
1. Ensure API domain is in CORS origins
2. Check `WEB_BASE_URL` environment variable
3. Verify cookies have correct domain

## Security Best Practices

1. **Use HTTPS** - Never use HTTP in production
2. **Strong Client Secret** - Use generated secret, don't reuse
3. **Short Token Lifetime** - Keep access tokens short-lived
4. **Validate State** - Always verify state parameter
5. **Secure Cookies** - Use httpOnly, Secure, SameSite

## Advanced Configuration

### Custom Claims

To add custom claims to the token:

1. In Authentik, go to **Customization** → **Property Mappings**
2. Create new **Scope Mapping**
3. Add custom attributes
4. Assign to provider

### Group Mapping

For team/organization support:

1. Configure group property mapping in Authentik
2. Headquarter will sync groups on login
3. Use groups for authorization

### Multiple Applications

If running multiple environments:

1. Create separate applications in Authentik
2. Use different client IDs
3. Configure environment-specific redirect URIs

## Testing

### Manual Test

1. Visit `https://app.yourdomain.com`
2. Click "Login"
3. Should redirect to Authentik
4. Login with Authentik credentials
5. Should redirect back to app, logged in

### API Test

```bash
# Check auth endpoint
curl https://api.yourdomain.com/auth/me
# Should return 401 (not authenticated)

# After login, should return user data
curl https://api.yourdomain.com/auth/me --cookie "session=..."
```

## Resources

- [Authentik Documentation](https://goauthentik.io/docs/)
- [OAuth2 Provider Setup](https://goauthentik.io/docs/providers/oauth2/)
- [Headquarter Auth Documentation](../features/auth.md)
