# Single Sign-On (SSO)

CoderFlow supports Single Sign-On via OpenID Connect (OIDC), allowing users to authenticate with your organization's identity provider.

## Overview

SSO provides:

- **Centralized authentication** — Users log in with existing corporate credentials
- **Automatic user provisioning** — New users are created on first login
- **Security compliance** — Leverage your IdP's MFA, conditional access, and audit logging

CoderFlow works with any OIDC-compliant identity provider, including Microsoft Entra ID, Okta, Google Workspace, and Auth0.

## VS Code Extension

When SSO is enabled, the VS Code extension profile manager shows a **Sign in with SSO** option. The extension opens a browser window to complete the SSO flow, then exchanges the approved session for an API key to store in the profile. This works even if local username/password login is disabled.

## Configuration Methods

SSO can be configured in two ways:

- **Web UI** — Configure through the Settings page (recommended)
- **Configuration file** — Edit `oidc.json` directly in your setup repository

Both methods produce the same result. The Web UI is recommended for most users as it provides validation and a guided setup experience.

## Configuring via Web UI

1. Navigate to **Settings → Single Sign-On**
2. Configure the **Connection** tab:
   - Enable SSO
   - Select your identity provider (or Custom for other providers)
   - Enter your Client ID, Client Secret, and Issuer URL
   - Use **Test Connection** to verify your settings
5. Configure the **User Provisioning** tab:
   - Enable/disable auto-provisioning
   - Set the default role for new users
   - Choose whether to allow local login alongside SSO
6. Click **Save** to save and apply changes immediately

## Configuring via File

Create an `oidc.json` file in your setup repository root:

```json
{
  "enabled": true,
  "display_name": "Sign in with Microsoft",
  "client_id": "your-client-id",
  "client_secret": "your-client-secret",
  "issuer": "https://login.microsoftonline.com/{tenant-id}/v2.0",
  "scopes": ["openid", "profile", "email"],
  "auto_provision": true,
  "default_role": "developer",
  "allow_local_auth": true
}
```

After saving the file, restart CoderFlow or use the Web UI to reload the configuration.

> **Security Note**: The `oidc.json` file contains secrets and is automatically excluded from git via `.gitignore`.

### Configuration Reference

| Option | Required | Default | Description |
|--------|----------|---------|-------------|
| `enabled` | Yes | — | Set to `true` to enable SSO |
| `display_name` | No | `"Sign in with SSO"` | Text displayed on the SSO button |
| `client_id` | Yes | — | Application/client ID from your identity provider |
| `client_secret` | Yes | — | Client secret from your identity provider |
| `issuer` | Yes | — | OIDC issuer URL (used for discovery) |
| `scopes` | No | `["openid", "profile", "email"]` | OAuth scopes to request |
| `auto_provision` | No | `true` | Automatically create users on first SSO login |
| `default_role` | No | `"developer"` | Role assigned to auto-provisioned users |
| `allow_local_auth` | No | `true` | Show local login form alongside SSO button |

## Microsoft Entra ID Setup

### 1. Create App Registration

1. Go to [Azure Portal](https://portal.azure.com)
2. Navigate to **Microsoft Entra ID** > **App registrations** > **New registration**
3. Configure the registration:
   - **Name**: `CoderFlow` (or your preferred name)
   - **Supported account types**: Single tenant (recommended for enterprise)
   - **Redirect URI**: Select **Web** and enter `https://{your-coderflow-host}/auth/oidc/callback`
4. Click **Register**
5. Note the **Application (client) ID** and **Directory (tenant) ID** from the Overview page

### 2. Create Client Secret

1. In your app registration, go to **Certificates & secrets**
2. Click **New client secret**
3. Add a description and select an expiration period
4. Click **Add**
5. Copy the secret **Value** immediately (it won't be shown again)

### 3. Configure CoderFlow

**Via Web UI:**
1. Go to **Settings → Single Sign-On**
2. Select **Microsoft Entra ID (Azure AD)** as the provider
3. Enter your Client ID and Client Secret
4. Replace `{tenant-id}` in the Issuer URL with your Directory (tenant) ID
5. Click **Save**

**Via configuration file:**

Create `oidc.json` in your setup repository:

```json
{
  "enabled": true,
  "display_name": "Sign in with Microsoft",
  "client_id": "{your-application-client-id}",
  "client_secret": "{your-client-secret-value}",
  "issuer": "https://login.microsoftonline.com/{your-tenant-id}/v2.0",
  "scopes": ["openid", "profile", "email"],
  "auto_provision": true,
  "default_role": "developer",
  "allow_local_auth": true
}
```

## Other Identity Providers

### Okta

**Issuer URL:** `https://{your-okta-domain}/oauth2/default`

In Okta Admin Console:
1. Create a new **Web** application
2. Set the redirect URI to `https://{your-coderflow-host}/auth/oidc/callback`
3. Copy the Client ID and Client Secret

### Google Workspace

**Issuer URL:** `https://accounts.google.com`

In Google Cloud Console:
1. Create OAuth 2.0 credentials (Web application type)
2. Add `https://{your-coderflow-host}/auth/oidc/callback` to authorized redirect URIs
3. Copy the Client ID and Client Secret

### Generic OIDC Provider

For other OIDC-compliant providers, you need:

- **Issuer URL**: Must support OIDC discovery (`.well-known/openid-configuration`)
- **Client ID and Secret**: From your provider's application registration
- **Redirect URI**: `https://{your-coderflow-host}/auth/oidc/callback`

## User Provisioning

### Auto-Provisioning Enabled (Default)

When auto-provisioning is enabled, CoderFlow automatically creates a user account on first SSO login:

- **Username**: Derived from email (e.g., `john.doe@company.com` becomes `johndoe`)
- **Email**: From the identity provider's claims
- **Name**: From the identity provider's claims
- **Role**: Set to the configured default role (defaults to `developer`)

The user can immediately access CoderFlow based on their assigned role.

### Auto-Provisioning Disabled

When auto-provisioning is disabled, users must be created in CoderFlow before they can log in via SSO. Create users with matching email addresses:

```bash
coder-server create-user --username=johndoe --email=john.doe@company.com --name="John Doe" --role=developer
```

SSO login will fail with "user not found" if no matching user exists.

### Updating User Information

When an existing user logs in via SSO, CoderFlow updates their display name if it changed in the identity provider. Other fields (username, role, permissions) are managed within CoderFlow.

## SSO-Only Mode

To enforce SSO and hide the local login form, disable "Allow local login" in the Web UI or set `allow_local_auth` to `false` in the configuration file.

> **Important**: Ensure at least one admin user can authenticate via SSO before disabling local auth. If locked out, re-enable local auth through the configuration file and restart the server.

## Removing SSO

To disable SSO:

**Via Web UI:**
1. Go to **Settings → Single Sign-On**
2. Click **Remove SSO**

**Via file:**
Delete the `oidc.json` file from your setup repository and restart CoderFlow.

## Troubleshooting

### "Redirect URI mismatch" Error

The redirect URI in your identity provider must exactly match CoderFlow's callback URL:

```
https://{your-host}/auth/oidc/callback
```

Common issues:
- HTTP vs HTTPS mismatch
- Missing or extra trailing slash
- Wrong port number
- Hostname mismatch (e.g., `localhost` vs `127.0.0.1`)

### "Invalid or expired state" Error

This occurs when:
- The login took too long (over 10 minutes)
- The user refreshed the page during login
- Browser cookies are blocked

Solution: Return to the login page and try again.

### "User not found" Error

This appears when auto-provisioning is disabled and no user with the SSO email exists in CoderFlow. Either:
- Enable auto-provisioning, or
- Create the user manually with the correct email address

### "Missing email claim" Error

The identity provider isn't returning the user's email. Ensure:
- The `email` scope is included in your configuration
- The user has an email address in the identity provider
- The app registration has permission to read email (check API permissions in Azure)

### SSO Button Not Appearing

Verify that:
- SSO is enabled in the configuration
- The server has loaded the configuration (check server logs)
- Use **Test Connection** in the Web UI to verify the issuer URL is accessible
