Skip to content

Teams and Roles Auto-Provisioning via Entra ID SSO #315

Closed

Description

@larryro

Summary

Implement automatic provisioning of teams and roles based on Entra ID attributes during SSO authentication. When users log in via Microsoft Entra, the system will automatically sync their roles (from App Roles) and team memberships (from Groups) to the local database.

Goals

  • Use Better Auth official SSO plugin for OIDC/SAML authentication
  • Auto-assign roles based on Entra App Roles
  • Auto-create teams and sync memberships based on Entra Groups
  • Add SSO configuration UI in Settings → Integrations
  • Maintain compatibility with existing Email and OneDrive integrations

Login Flow Change

Before (Social Provider):

User → Click "Sign in with Microsoft" → Microsoft auth → Login success

After (SSO Plugin):

User → Enter email → Domain detection → Auto-redirect to Entra → Login success
    → organizationProvisioning (join org + set role)
    → provisionUser callback (sync teams)

Data Sources

  • Roles: App Roles (via getRole callback from userInfo.roles)
  • Teams: Groups (via provisionUser callback calling Graph API)

Files to Create/Modify

New Files

File Purpose
convex/betterAuth/sso/team_sync.ts Team sync logic
convex/sso_providers/queries.ts SSO provider queries
convex/sso_providers/mutations.ts SSO provider CRUD
app/features/settings/integrations/components/sso-card.tsx SSO config UI card
app/features/settings/integrations/components/sso-config-dialog.tsx SSO config dialog

Modified Files

File Changes
convex/auth.ts Add SSO plugin config
app/features/settings/integrations/components/integrations-settings.tsx Add SSO card
docker-entrypoint.sh Add new env vars

Azure Configuration Required

API Permissions

  • GroupMember.Read.All (Delegated)
  • User.Read (Delegated)

App Roles to Define

Display Name Value Description
Administrator admin Full access
Developer developer Development access
Editor editor Content editing access
Member member Read-only access

Configuration

Minimal (2 env vars):

SSO_AUTO_PROVISION_ENABLED=true
SSO_DOMAIN=yourcompany.com

Optional:

SSO_EXCLUDE_GROUPS=All-Employees,Domain-Users
SSO_TEAM_MEMBERSHIP_MODE=sync  # or 'additive'

References

Activity

  1. larryro commented on Jan 31, 2026

    @larryro
    ContributorAuthor

    Teams and Roles Auto-Provisioning via Entra ID SSO

    Summary

    Implement automatic provisioning using Better Auth's official SSO plugin. When users log in via Entra ID, automatically sync roles and teams to the local database.

    Better Auth SSO Plugin Features

    Official plugin support (docs):

    • ✅ SAML/OIDC configuration
    • ✅ Organization auto-join (organizationProvisioning)
    • ✅ Role mapping (getRole callback)
    • ✅ User provisioning (provisionUser callback)

    To implement: Team sync (in provisionUser callback)

    Current Architecture

    • Microsoft OAuth: Existing config in convex/auth.ts
    • Teams: team and teamMember tables
    • Roles: 5 levels (disabled, member, editor, developer, admin)

    Login Flow Change

    Before (Social Provider):

    User → Click "Sign in with Microsoft" button → Microsoft auth → Login success
    

    After (SSO Plugin):

    User → Enter email → Domain detection → Auto-redirect to Microsoft Entra → Login success
        → organizationProvisioning (join org + set role)
        → provisionUser callback (sync teams)
    

    UI Change: Login page needs email input field for domain-based SSO routing.

    High-Level Flow

    User → Enter email → Better Auth SSO Plugin (domain detection)
        → Microsoft Entra authentication
        → organizationProvisioning (join org + set role)
        → provisionUser callback (sync teams)
    

    Data Sources:

    • Role: App Roles (via getRole callback from userInfo.roles)
    • Teams: Groups (via provisionUser callback calling Graph API)

    Files to Modify/Create

    New Files

    File Purpose
    convex/betterAuth/sso/team_sync.ts Team sync logic
    convex/sso_providers/queries.ts SSO provider queries
    convex/sso_providers/mutations.ts SSO provider CRUD
    app/features/settings/integrations/components/sso-card.tsx SSO config UI card
    app/features/settings/integrations/components/sso-config-dialog.tsx SSO config dialog

    Modified Files

    File Changes
    convex/auth.ts Add SSO plugin configuration
    app/features/settings/integrations/components/integrations-settings.tsx Add SSO card
    docker-entrypoint.sh Add new env vars

    Implementation Steps

    Step 1: Install SSO Plugin Dependency

    npm install @better-auth/sso --workspace=@tale/platform

    Step 2: Configure SSO Plugin

    File: convex/auth.ts

    import { sso } from '@better-auth/sso';
    import { syncTeamsFromGroups } from './betterAuth/sso/team_sync';
    
    export const { auth, ...authHandlers } = betterAuth({
      // ... existing config ...
      plugins: [
        organizationPlugin({ /* ... */ }),
        accessControlPlugin({ /* ... */ }),
    
        // NEW: SSO plugin
        sso({
          // Organization auto-provisioning
          organizationProvisioning: {
            disabled: false,
            defaultRole: 'member',
    
            // Get role from App Roles
            getRole: async ({ userInfo }) => {
              const roles = userInfo.roles || [];
              const roleOrder = ['admin', 'developer', 'editor', 'member'];
              for (const r of roleOrder) {
                if (roles.includes(r)) return r;
              }
              return 'member';
            },
          },
    
          // User provisioning callback - sync teams
          provisionUser: async ({ user, userInfo, token }) => {
            if (process.env.SSO_AUTO_PROVISION_ENABLED !== 'true') return;
    
            // Fetch Groups from Graph API and sync as teams
            await syncTeamsFromGroups({
              userId: user.id,
              accessToken: token.accessToken,
              excludeGroups: (process.env.SSO_EXCLUDE_GROUPS || '').split(','),
            });
          },
        }),
      ],
    
      // Update OAuth scopes
      socialProviders: {
        microsoft: {
          // ... existing config ...
          scope: [
            'offline_access',
            'email',
            'https://graph.microsoft.com/Files.Read',
            'https://graph.microsoft.com/GroupMember.Read.All', // NEW
          ],
        },
      },
    });

    Step 3: Create Team Sync Logic

    File: convex/betterAuth/sso/team_sync.ts

    import { MutationCtx } from '../../_generated/server';
    import * as AuditLogHelpers from '../../audit_logs/helpers';
    
    interface SyncTeamsArgs {
      userId: string;
      accessToken: string;
      excludeGroups: string[];
    }
    
    export async function syncTeamsFromGroups(
      ctx: MutationCtx,
      args: SyncTeamsArgs,
    ) {
      const { userId, accessToken, excludeGroups } = args;
    
      // 1. Get the single organization in the system
      const orgs = await ctx.db.query('organization').take(2);
      if (orgs.length !== 1) {
        console.warn('[SSO] No single organization found, skipping team sync');
        return;
      }
      const organizationId = orgs[0]._id;
    
      // 2. Fetch user groups from Graph API
      const groups = await fetchEntraGroups(accessToken);
    
      // 3. Filter excluded groups
      const syncableGroups = groups.filter(
        g => !excludeGroups.some(ex => ex.toLowerCase() === g.displayName.toLowerCase())
      );
    
      // 4. Sync team memberships
      const teamNames: string[] = [];
      for (const group of syncableGroups) {
        const teamName = group.displayName;
        teamNames.push(teamName);
    
        // Find or create team
        let team = await findTeamByName(ctx, teamName, organizationId);
        if (!team) {
          team = await createTeam(ctx, teamName, organizationId);
        }
    
        // Add membership
        if (!await isTeamMember(ctx, team._id, userId)) {
          await addTeamMember(ctx, team._id, userId);
        }
      }
    
      // 5. Remove stale team memberships (sync mode)
      if (process.env.SSO_TEAM_MEMBERSHIP_MODE !== 'additive') {
        await removeStaleTeamMemberships(ctx, userId, teamNames, organizationId);
      }
    }
    
    async function fetchEntraGroups(accessToken: string) {
      const response = await fetch(
        'https://graph.microsoft.com/v1.0/me/memberOf',
        { headers: { Authorization: `Bearer ${accessToken}` } }
      );
      const data = await response.json();
      return data.value
        .filter((m: any) => m['@odata.type'] === '#microsoft.graph.group')
        .map((g: any) => ({ id: g.id, displayName: g.displayName }));
    }
    
    // Helper functions (findTeamByName, createTeam, isTeamMember, etc.)
    // ... implement using Better Auth adapter

    Step 4: Register Entra SSO Provider

    SSO providers are stored in the ssoProvider table. Choose one registration method:

    Option A: Direct Database Insert (recommended for automated deployment)

    Create a seed script or migration to insert into the ssoProvider table:

    // convex/seed/sso_provider.ts
    export async function seedSSOProvider(ctx: MutationCtx) {
      const existing = await ctx.db
        .query('ssoProvider')
        .withIndex('providerId', q => q.eq('providerId', 'entra-id'))
        .first();
    
      if (existing) return; // Already exists
    
      await ctx.db.insert('ssoProvider', {
        providerId: 'entra-id',
        issuer: `https://login.microsoftonline.com/${process.env.AUTH_MICROSOFT_ENTRA_ID_TENANT_ID}/v2.0`,
        domain: process.env.SSO_DOMAIN,
        oidcConfig: JSON.stringify({
          clientId: process.env.AUTH_MICROSOFT_ENTRA_ID_ID,
          clientSecret: process.env.AUTH_MICROSOFT_ENTRA_ID_SECRET,
          scopes: ['openid', 'email', 'profile', 'GroupMember.Read.All'],
        }),
        createdAt: Date.now(),
      });
    }

    Option B: Via API

    await auth.api.registerSSOProvider({
      body: {
        providerId: 'entra-id',
        issuer: `https://login.microsoftonline.com/${process.env.AUTH_MICROSOFT_ENTRA_ID_TENANT_ID}/v2.0`,
        domain: process.env.SSO_DOMAIN,
        oidcConfig: {
          clientId: process.env.AUTH_MICROSOFT_ENTRA_ID_ID,
          clientSecret: process.env.AUTH_MICROSOFT_ENTRA_ID_SECRET,
          scopes: ['openid', 'email', 'profile', 'GroupMember.Read.All'],
        },
      },
    });

    ssoProvider Table Schema:

    Field Type Description
    providerId string Unique identifier (e.g., 'entra-id')
    issuer string OIDC issuer URL
    domain string Associated domain (e.g., 'yourcompany.com')
    oidcConfig string (JSON) OIDC configuration
    organizationId string? Associated organization (optional)
    createdAt number Creation timestamp

    Step 5: Add SSO Configuration UI

    File: app/features/settings/integrations/components/sso-card.tsx

    export function SSOCard() {
      const ssoProvider = useQuery(api.sso_providers.get);
      const [isDialogOpen, setIsDialogOpen] = useState(false);
    
      return (
        <Card>
          <CardHeader>
            <CardTitle>Single Sign-On (SSO)</CardTitle>
            <CardDescription>
              {t('settings.integrations.sso.description')}
            </CardDescription>
          </CardHeader>
          <CardContent>
            {ssoProvider ? (
              <div className="space-y-2">
                <Badge variant="success">{t('common.connected')}</Badge>
                <p className="text-sm text-muted-foreground">
                  {t('settings.integrations.sso.domain')}: {ssoProvider.domain}
                </p>
              </div>
            ) : (
              <p className="text-sm text-muted-foreground">
                {t('settings.integrations.sso.not_configured')}
              </p>
            )}
          </CardContent>
          <CardFooter>
            <Button onClick={() => setIsDialogOpen(true)}>
              {ssoProvider ? t('common.edit') : t('common.configure')}
            </Button>
          </CardFooter>
    
          <SSOConfigDialog open={isDialogOpen} onOpenChange={setIsDialogOpen} />
        </Card>
      );
    }

    File: app/features/settings/integrations/components/sso-config-dialog.tsx

    Form fields:

    • Provider ID (auto-generated or custom)
    • Domain (e.g., yourcompany.com)
    • Issuer URL (Entra: https://login.microsoftonline.com/{tenant}/v2.0)
    • Client ID
    • Client Secret
    • Auto-provisioning toggle (teams/roles sync)
    • Excluded groups list

    Step 6: SSO Provider CRUD API

    File: convex/sso_providers/queries.ts

    export const get = query({
      args: { organizationId: v.string() },
      handler: async (ctx, args) => {
        // Get SSO provider for current organization
        return await ctx.db
          .query('ssoProvider')
          .withIndex('organizationId', q => q.eq('organizationId', args.organizationId))
          .first();
      },
    });

    File: convex/sso_providers/mutations.ts

    export const upsert = mutation({
      args: {
        providerId: v.string(),
        domain: v.string(),
        issuer: v.string(),
        clientId: v.string(),
        clientSecret: v.string(),
        autoProvisionEnabled: v.boolean(),
        excludeGroups: v.array(v.string()),
      },
      handler: async (ctx, args) => {
        // Verify user is admin
        // Create or update ssoProvider record
      },
    });

    Step 7: Update Docker Configuration

    File: docker-entrypoint.sh

    ENV_VARS_TO_SYNC=(
      # ... existing ...
      "SSO_AUTO_PROVISION_ENABLED"
      "SSO_EXCLUDE_GROUPS"
      "SSO_TEAM_MEMBERSHIP_MODE"
    )

    Note: SSO_DOMAIN no longer needed as it's configured via UI

    Entra ID App Registration Requirements

    In Azure Portal, the app registration needs:

    1. API Permissions

    • GroupMember.Read.All (Delegated) - Read user group memberships
    • User.Read (Delegated) - Already present

    2. App Roles Definition

    Create the following roles in "App roles" page (values must match Tale role names):

    Display Name Value Description
    Administrator admin Full access
    Developer developer Development access
    Editor editor Content editing access
    Member member Read-only access

    3. Assign Users to App Roles

    In "Enterprise applications" → Your app → "Users and groups", assign users/groups to corresponding roles

    Design Decisions

    Decision Choice Rationale
    Implementation Better Auth official SSO plugin Uses official provisionUser and getRole callbacks
    Role source App Roles via getRole Official callback, gets from userInfo.roles
    Team source Groups via Graph API Called in provisionUser callback
    Team naming Entra group name = Tale team name Zero config, fully automatic
    Membership removal Default sync mode Full sync, keeps consistent with Entra

    Error Handling

    Scenario Handling
    Graph API call fails Log error, skip sync, continue with auth (don't block login)
    Group in exclude list Skip that group, don't create team
    No App Role assigned Default to member role
    DB write failure Log error, continue auth (partial sync > login failure)
    No organization or multiple orgs Skip sync, log warning

    Audit Log Events

    New actions for traceability:

    • sso_team_provisioned - Team created from Entra group
    • sso_team_membership_added - User added to team
    • sso_team_membership_removed - User removed from team
    • sso_role_synced - Role updated from Entra groups

    All with metadata: { source: 'entra_oauth', entraGroupId: '...' } for filtering.

    Verification

    1. Unit tests for group/role mapping logic
    2. Integration test with mocked Graph API response
    3. Manual test:
      • Configure Entra app with test groups and App Roles
      • Login → verify teams created and role assigned
      • Change groups/roles in Entra → re-login → verify sync
      • Check audit logs for provisioning events

    Organization Handling

    Single-company deployment: Auto-detect the single organization in the system.

    • No organization ID configuration needed
    • System automatically queries organization table and uses the only existing org
    • If no organization or multiple organizations exist, skip sync and log warning

    Compatibility with Existing Integrations

    Feature Impact Notes
    Email (Outlook) ✅ No impact Uses separate OAuth flow, stored in emailProviders table
    OneDrive ⚠️ Need correct scopes Depends on user account token, SSO config must include Files.Read scope

    OneDrive Compatibility: Include necessary scopes in SSO provider config:

    oidcConfig: {
      scopes: [
        'openid', 'email', 'profile',
        'offline_access',
        'https://graph.microsoft.com/Files.Read',      // OneDrive read
        'https://graph.microsoft.com/GroupMember.Read.All', // Group membership
      ],
    }

    Configuration (Simplified)

    Minimal - 2 env vars:

    SSO_AUTO_PROVISION_ENABLED=true
    SSO_DOMAIN=yourcompany.com  # For domain association

    Automatic Logic:

    • Organization: Better Auth SSO plugin handles org association automatically
    • Role: getRole callback gets from userInfo.roles (App Roles)
    • Teams: provisionUser callback fetches Groups from Graph API and syncs

    Optional Configuration:

    # Exclude certain groups from team sync
    SSO_EXCLUDE_GROUPS=All-Employees,Domain-Users
    
    # Team sync mode: sync (full sync) or additive (only add, don't remove)
    SSO_TEAM_MEMBERSHIP_MODE=sync

    Critical Files Summary

    File Purpose
    convex/auth.ts Add SSO plugin configuration
    convex/betterAuth/sso/team_sync.ts NEW: Team sync logic
    convex/sso_providers/ NEW: SSO provider CRUD
    app/features/settings/integrations/components/sso-card.tsx NEW: SSO config UI
    docker-entrypoint.sh Add new env vars

    Sources

  2. added
    priority: high
    feat
    on Feb 1, 2026
  3. added 2 commits that reference this issue on Feb 3, 2026
    451ecad
    01976ed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    featpriority: high

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions