# Deployment Workflow

Step-by-step guide for deploying authentication and authorization configuration.

| Property          | Value                                               |
| ----------------- | --------------------------------------------------- |
| **Goal**          | Deploy auth configuration in the correct order      |
| **Prerequisites** | API project created, Business Roles identified      |
| **Time Estimate** | 30-45 minutes (first time), 10-15 minutes (updates) |
| **Difficulty**    | Intermediate                                        |

---

## 📋 Overview

Authorization configuration requires deploying multiple components in a specific order. Getting the order wrong results in errors like "Business Role not found" or "Application not registered."

### Deployment Order

```mermaid
flowchart TD
    A[1. Create Business Roles] --> B[2. Deploy Your API]
    B --> C[3. Assign Yourself Roles]
    C --> D[4. Generate Test Token]

    A -->|"Business Roles Repo"| A1["Creates Entra/Okta groups"]
    B -->|"API Pipeline"| B1["Deploys app + auth config"]
    C -->|"NP Roles Pipeline"| C1["Adds you to test roles"]
    D -->|"SAIF CLI or Pipeline"| D1["Get JWT for testing"]
```

!!! tip "Auth Runs Automatically"
    The API pipeline includes all auth deployments. You don't need to run a separate auth pipeline.

---

## Step 1: Create Business Roles (If Needed)

Before your app can grant access to users, the Business Roles must exist.

!!! info "Skip if Business Roles Already Exist"
    If you're using existing Business Roles (like `Claims Adjuster`), skip to Step 2.

### Check if Business Role Exists

1. Look in your project's business roles repository:
   - Corporate: `{Project}-okta-business-roles-corp`
   - External: `{Project}-okta-business-roles-external`

2. Check `infra/okta/okta-business-roles.yml` for the role you need

### Create New Business Role

If the role doesn't exist, add it to the business roles repository:

=== "Corporate (Entra ID)"

    **File:** `infra/okta/okta-business-roles.yml`

    ```yaml
    BusinessRoles:
      - Name: "Premium Auditor"
        Description: "Staff who perform premium audits"
        RoleSets:
          - Division: Audit Division
            Roles:
              - Premium Auditor
              - Senior Premium Auditor
        ManualUsers: []
    ```

=== "External (Okta)"

    **File:** `infra/okta/okta-business-roles.yml`

    ```yaml
    BusinessRoles:
      - Name: Policy Holder
        Description: Policyholders who can view their policy information
        Roles:
          - PolicyholderAccess
        ManualUsers: []
    ```

### Deploy Business Roles

Run the business roles pipeline to create the roles in the identity provider.

!!! warning "Must Complete Before Step 3"
    Business Roles must be deployed before the auth pipeline can reference them.

---

## Step 2: Deploy Your API

The API pipeline deploys both your application AND all auth configuration in a single run. The orchestrator handles the correct ordering automatically.

### What Gets Deployed

The API pipeline deploys these components in order:

| Stage                  | What It Does                                     |
| ---------------------- | ------------------------------------------------ |
| `auth_ext_okta_client` | Creates Okta authorization server and client     |
| `api_infra`            | Creates app registration, app service, resources |
| `api_container`        | Deploys your container image                     |
| `auth_ext_app`         | Configures app-to-app authorization (Okta)       |
| `auth_ext_user`        | Maps Business Roles to Okta groups               |
| `auth_corp`            | Configures Entra ID roles and permissions        |

### Run API Pipeline

```
Pipeline: azure-dotnet-api.yml
Environments: Deploy to at least Test (all environments for production auth)
```

### Verify Deployment

After deployment, confirm:

1. **Entra ID**: App registration exists with app roles in Azure Portal → Enterprise Applications
2. **Okta**: Authorization server and groups exist in Okta Admin

### What Gets Configured

| Action                   | Corporate (Entra)                 | External (Okta)                                       |
| ------------------------ | --------------------------------- | ----------------------------------------------------- |
| Creates App Roles        | From `infra/api/config.yml`       | From `infra/auth/ext/okta-client/user_groups.yml`     |
| Creates Scopes           | From `infra/api/config.yml`       | From `infra/auth/ext/okta-client/scopes.yml`          |
| Maps Business Roles      | From `infra/auth/corp/config.yml` | From `infra/auth/ext/user/business-role-app-role.yml` |
| Authorizes Upstream Apps | From `infra/auth/corp/config.yml` | From `infra/auth/ext/app/authorized-apps.yml`         |

!!! tip "Auth-Only Updates"
    If you only changed auth configuration (not application code), you can run the standalone auth pipeline instead:

    ```
    Pipeline: azure-pipelines-auth.yml
    ```

    This is faster than a full API deployment when you're just updating roles or permissions.

---

## Step 3: Assign Yourself Roles (Non-Production)

For testing, assign yourself the Business Roles needed to access your API.

### Using NP Roles Pipeline

1. Create or locate your personal test tools repository
2. Edit `infra/my-roles.yml`:

```yaml
Username: yourMailId
Roles:
  - Premium Auditor
  - Claims Adjuster
```

3. Run the NP roles pipeline

### Verify Role Assignment

1. Log out and log back in (to refresh token)
2. Check your group memberships in Okta or Entra ID

For detailed instructions, see [Non-Production Role Assignment](../testing/non-production-role-assignment.md).

---

## Step 4: Generate Test Token

Generate a JWT token to test your API.

### Corporate Token (Entra ID)

Use the SAIF CLI:

```powershell
saif auth generate --name <application-name>
```

**Example:**

```powershell
saif auth generate --name it-api-exp-myapp-test
```

### External Token (Okta)

Use the Azure DevOps pipeline in your personal test tools repository.

For detailed instructions, see [Create JWT for Testing APIs](../testing/create-jwt-for-testing-apis.md).

### Test Your API

Use the token in your HTTP client:

```
Authorization: Bearer <your-token>
```

---

## 🔍 Common Errors and Solutions

### "Business Role Not Found"

```
Error: No group found matching specified filter
(displayName eq 'bus-role-np.developer' and securityEnabled eq true)
```

**Cause:** Business Role doesn't exist in the identity provider.

**Solution:**
1. Create the Business Role in the business roles repository (Step 1)
2. Deploy the business roles pipeline
3. Re-run your API pipeline (or the standalone auth pipeline)

### "Application Not Registered"

**Cause:** Trying to authorize an app that hasn't been deployed yet.

**Solution:**
1. Deploy the upstream app first
2. Then configure authorized_apps in your API
3. Re-run your API pipeline

### "Invalid Token" or "401 Unauthorized"

**Cause:** Token missing required scopes or roles.

**Solution:**
1. Verify you're assigned the correct Business Roles (Step 3)
2. Generate a fresh token (Step 4)
3. Check token at [jwt.io](https://jwt.io) to verify claims

### Auth Pipeline Skipped

**Cause:** Pipeline detected no changes to auth configuration files.

**Solution:**
- Force a change by adding a comment to a config file, or
- Manually trigger the auth stages in the pipeline

---

## 📋 Quick Reference: File Locations

| Configuration         | Corporate (Entra)                         | External (Okta)                                  |
| --------------------- | ----------------------------------------- | ------------------------------------------------ |
| **App Roles**         | `infra/api/config.yml`                    | `infra/auth/ext/okta-client/user_groups.yml`     |
| **Scopes**            | `infra/api/config.yml`                    | `infra/auth/ext/okta-client/scopes.yml`          |
| **Business Role Map** | `infra/auth/corp/config.yml`              | `infra/auth/ext/user/business-role-app-role.yml` |
| **Authorized Apps**   | `infra/auth/corp/config.yml`              | `infra/auth/ext/app/authorized-apps.yml`         |
| **Business Roles**    | `{Project}-okta-business-roles-corp` repo | `{Project}-okta-business-roles-external` repo    |

---

## 📋 Deployment Checklist

Use this checklist for new API deployments:

- [ ] **Business Roles exist** in business roles repository (or using existing roles)
- [ ] **Business Roles deployed** via business roles pipeline
- [ ] **App Roles defined** in `infra/api/config.yml`
- [ ] **Scopes defined** in `infra/api/config.yml` (if other apps call your API)
- [ ] **Business Roles mapped** in corp and ext auth configs
- [ ] **Authorized apps configured** (if other apps call your API)
- [ ] **API deployed** to target environment(s) (includes auth configuration)
- [ ] **Test roles assigned** to yourself
- [ ] **Test token generated** and API tested

---

## 📚 Related Documentation

- [Aspire Publish](../../development/aspire-publish.md) - Generate pipelines and auth config from your AppHost
- [Aspire Security Configuration](aspire-security-configuration.md) - Define security configuration in C#
- [Business Roles](business-roles.md) - How Business Roles work and configuration
- [User Permissions](user-permissions.md) - Map Business Roles to App Roles
- [App Permissions](app-permissions.md) - Configure scopes and authorize apps
- [Create JWT for Testing](../testing/create-jwt-for-testing-apis.md) - Generate test tokens
- [Non-Production Roles](../testing/non-production-role-assignment.md) - Assign test roles
- [Authorization Concepts](../../../reference/authorization.md) - Scopes vs. Roles explained
