# Authentik OIDC Setup

Complete guide to configuring Authentik OIDC authentication for Mosaic Stack.

## Overview

Mosaic Stack uses **BetterAuth** with **OpenID Connect (OIDC)** for authentication. Authentik serves as the identity provider for SSO capabilities.

## Prerequisites

- Authentik instance (self-hosted or cloud)
- Admin access to Authentik
- Mosaic Stack installed and running

## Step 1: Install Authentik (Optional)

If you don't have an existing Authentik instance:

### Docker Compose Method

```bash
# Create Authentik directory
mkdir ~/authentik && cd ~/authentik

# Download compose file
curl -o docker-compose.yml https://goauthentik.io/docker-compose.yml

# Generate secret key
echo "AUTHENTIK_SECRET_KEY=$(openssl rand -base64 60)" >> .env

# Start Authentik
docker compose up -d

# Wait for startup (~30 seconds)
docker compose logs -f
```

**Access Authentik:**

- URL: http://localhost:9000/if/flow/initial-setup/
- Create admin account during initial setup

### Alternative: Use Hosted Authentik

Sign up at [goauthentik.io](https://goauthentik.io) for managed Authentik.

## Step 2: Create OAuth2 Provider

1. **Log in to Authentik** as admin

2. **Navigate to Applications** → **Providers**

3. **Click "Create"** and select **OAuth2/OpenID Provider**

4. **Configure Provider:**

   | Field                          | Value                                                  |
   | ------------------------------ | ------------------------------------------------------ |
   | **Name**                       | Mosaic Stack                                           |
   | **Authorization flow**         | default-provider-authorization-implicit-consent        |
   | **Client type**                | Confidential                                           |
   | **Client ID**                  | (auto-generated, save this)                            |
   | **Client Secret**              | (auto-generated, save this)                            |
   | **Redirect URIs**              | `http://localhost:3001/auth/oauth2/callback/authentik` |
   | **Scopes**                     | `openid`, `email`, `profile`                           |
   | **Subject mode**               | Based on User's UUID                                   |
   | **Include claims in id_token** | ✅ Enabled                                             |

5. **Click "Create"**

6. **Save** the Client ID and Client Secret for Step 4

## Step 3: Create Application

1. **Navigate to Applications** → **Applications**

2. **Click "Create"**

3. **Configure Application:**

   | Field          | Value                                     |
   | -------------- | ----------------------------------------- |
   | **Name**       | Mosaic Stack                              |
   | **Slug**       | mosaic-stack                              |
   | **Provider**   | Select "Mosaic Stack" (created in Step 2) |
   | **Launch URL** | `http://localhost:3000`                   |

4. **Click "Create"**

## Step 4: Configure Mosaic Stack

Update your `.env` file:

```bash
# Authentik OIDC Configuration
OIDC_ISSUER=http://localhost:9000/application/o/mosaic-stack/
OIDC_CLIENT_ID=<your-client-id-from-step-2>
OIDC_CLIENT_SECRET=<your-client-secret-from-step-2>
OIDC_REDIRECT_URI=http://localhost:3001/auth/oauth2/callback/authentik
```

**Important Notes:**

- `OIDC_ISSUER` must end with a trailing slash `/`
- Replace `<your-client-id>` and `<your-client-secret>` with actual values from Step 2
- `OIDC_REDIRECT_URI` must exactly match what you configured in Authentik

### Production Configuration

For production deployments:

```bash
OIDC_ISSUER=https://auth.example.com/application/o/mosaic-stack/
OIDC_CLIENT_ID=prod-client-id
OIDC_CLIENT_SECRET=prod-client-secret
OIDC_REDIRECT_URI=https://mosaic.example.com/auth/oauth2/callback/authentik
```

Update Authentik redirect URIs to match your production URL.

## Step 5: Restart Mosaic Stack

```bash
# Local development
pnpm dev:api

# Docker
docker compose restart api
```

## Step 6: Test Authentication

### Method 1: Web UI (when implemented)

1. Navigate to `http://localhost:3000`
2. Click "Sign In"
3. You'll be redirected to Authentik
4. Log in with your Authentik credentials
5. Authorize the application
6. You'll be redirected back to Mosaic Stack

### Method 2: API Endpoint

```bash
# Initiate OIDC flow
curl http://localhost:3001/auth/oauth2/callback/authentik

# This will return a redirect URL to Authentik
```

### Method 3: Direct Email/Password (Development)

```bash
# Create user via API (development only)
curl -X POST http://localhost:3001/auth/sign-up \
  -H "Content-Type: application/json" \
  -d '{
    "email": "test@example.com",
    "password": "SecurePass123!",
    "name": "Test User"
  }'

# Sign in
curl -X POST http://localhost:3001/auth/sign-in \
  -H "Content-Type: application/json" \
  -d '{
    "email": "test@example.com",
    "password": "SecurePass123!"
  }'

# Response includes session token
{
  "user": {
    "id": "...",
    "email": "test@example.com",
    "name": "Test User"
  },
  "session": {
    "token": "eyJhbGc...",
    "expiresAt": "..."
  }
}
```

## Advanced Configuration

### Custom Scopes

To request additional user information:

1. In Authentik, navigate to **Customization** → **Property Mappings**
2. Create custom **Scope Mapping**
3. Add scope to provider configuration
4. Update Mosaic Stack to request the scope

### Multi-Factor Authentication (MFA)

Enable MFA in Authentik:

1. **Navigate to Flows & Stages** → **Flows**
2. Edit **default-authentication-flow**
3. Add **Multi-Factor Authentication** stage
4. Configure MFA methods (TOTP, WebAuthn, etc.)

Users will be prompted for MFA during login.

### Custom Login Page

Customize Authentik's login page:

1. **Navigate to Customization** → **Brands**
2. Edit default brand
3. Customize logo, title, and theme
4. Save changes

## Troubleshooting

### Error: "Invalid redirect URI"

**Cause:** Redirect URI in `.env` doesn't match Authentik configuration

**Fix:**

```bash
# Ensure exact match (including http vs https)
# In Authentik: http://localhost:3001/auth/oauth2/callback/authentik
# In .env: OIDC_REDIRECT_URI=http://localhost:3001/auth/oauth2/callback/authentik
```

### Error: "Invalid client credentials"

**Cause:** Incorrect client ID or secret

**Fix:**

1. Double-check Client ID and Secret in Authentik provider
2. Copy values exactly (no extra spaces)
3. Update `.env` with correct values
4. Restart API

### Error: "OIDC discovery failed"

**Cause:** `OIDC_ISSUER` incorrect or Authentik not accessible

**Fix:**

```bash
# Ensure OIDC_ISSUER ends with /
# Test discovery endpoint
curl http://localhost:9000/application/o/mosaic-stack/.well-known/openid-configuration

# Should return JSON with OIDC configuration
```

### Users Can't Access Application

**Cause:** User doesn't have permission in Authentik

**Fix:**

1. In Authentik, go to **Directory** → **Users**
2. Select user
3. Click **Assigned to applications**
4. Add "Mosaic Stack" application

Or enable **Superuser privileges** for the user (development only).

### Session Expires Too Quickly

**Cause:** JWT expiration set too low

**Fix:**

```bash
# In .env, increase expiration
JWT_EXPIRATION=7d  # 7 days instead of 24h

# Restart API
```

## Security Considerations

### Production Checklist

- [ ] Use HTTPS for all URLs
- [ ] Configure CORS properly
- [ ] Use strong client secret (rotate regularly)
- [ ] Enable MFA for admin accounts
- [ ] Review Authentik audit logs regularly
- [ ] Limit redirect URIs to exact matches
- [ ] Use environment-specific client credentials
- [ ] Enable rate limiting on auth endpoints

### Recommended Authentik Settings

```yaml
# In Authentik provider configuration:
- Access token validity: 30 minutes
- Refresh token validity: 30 days
- Include claims in ID token: Enabled
- Subject mode: Based on User's UUID
- Signing algorithm: RS256
```

## User Management

### Create User in Authentik

1. **Navigate to Directory** → **Users**
2. **Click "Create"**
3. Fill in user details:
   - Username
   - Email (required for OIDC)
   - Name
4. **Click "Create"**
5. User can now log in to Mosaic Stack

### Assign Users to Application

1. Go to **Applications** → **Applications**
2. Select "Mosaic Stack"
3. Click **Policy / Group / User Bindings**
4. **Click "Bind existing policy"**
5. Select users or groups
6. **Click "Create"**

## Next Steps

- **Review Authentication Flow** — [Architecture → Authentication](../../3-architecture/2-authentication/1-betterauth.md)
- **Start Development** — [Development → Workflow](../../2-development/1-workflow/1-branching.md)
- **Explore API** — [API → Authentication](../../4-api/2-authentication/1-endpoints.md)
