Enterprise SSO & SCIM: SSO and SCIM provisioning for B2B enterprise customers with directory synchronization --- # DOCUMENT BOUNDARY --- # What is Modular SSO > Add SAML and OIDC enterprise SSO to an app that keeps its own users and sessions. See what Scalekit runs, what your app keeps, and the path to build it. Modular SSO adds enterprise single sign-on (SSO) to an app that already signs users in. Your app keeps its users, its sessions and its login page, whether that’s your own code or an auth system such as Auth0, Amazon Cognito, Firebase or Supabase. Scalekit links your app to each enterprise customer’s identity provider (IdP), such as Okta or Microsoft Entra ID, over SAML or OIDC. Use Modular SSO when an enterprise customer asks for SSO and you don’t want to replace the login you have. Want Scalekit to run the whole login, with users, sessions and roles? Use [Full Stack Auth](/authenticate/fsa/quickstart/) instead. It includes SSO. ## What Scalekit runs and what your app keeps [Section titled “What Scalekit runs and what your app keeps”](#what-scalekit-runs-and-what-your-app-keeps) | Scalekit | Your app | | ------------------------------------------------------------------------------------------ | ---------------------------------------------------------------------- | | Connects to each customer’s IdP over SAML or OIDC | Stores your users in your own database | | Gives each customer’s IT admin a portal to set up their IdP | Creates the session after login and ends it at logout | | Returns the signed-in user’s profile in one format for every IdP | Decides each user’s roles and access, using attributes the IdP sends | | Sends each user to their company’s IdP, picked by organization, connection or email domain | Decides which users sign in with SSO and which use your existing login | The customer’s IdP enforces its own sign-in policies, such as multi-factor authentication (MFA). ## How a login works [Section titled “How a login works”](#how-a-login-works) ![The SSO flow: your app sends the user to Scalekit, Scalekit sends them to their company's identity provider, and the verified user comes back to your app](/.netlify/images?url=_astro%2F1.Bj4LD99k.png\&w=4936\&h=3744\&dpl=6aedac7ec39c4cadbcd1959e) 1. A user chooses to sign in with SSO in your app, for example by entering their work email. 2. Your app builds an authorization URL that names the user’s organization, connection or email domain, and redirects the user to it. 3. Scalekit sends the user to their company’s IdP, where they sign in. 4. The IdP sends the result to Scalekit, which redirects the user to your app’s callback URL with a one-time code. 5. Your app exchanges the code for the user’s profile, finds or creates the user in your database and starts its own session. Users can also start from their IdP’s dashboard, such as an Okta tile. Your app turns that into the same flow; see [IdP-initiated SSO](/sso/guides/idp-init-sso/). ## What you’ll build [Section titled “What you’ll build”](#what-youll-build) 1. [Quickstart](/authenticate/sso/add-modular-sso/): sign in a test user through the SSO simulator. 2. [How Modular SSO works](/authenticate/sso/how-it-works/): organizations, connections, domains and what your callback receives. 3. [Choose how to integrate](/authenticate/sso/choose-integration/): your own code, or Auth0, Cognito, Firebase or Supabase. 4. [Handle the callback and find the user](/authenticate/sso/handle-callback/): check the response, find or create the user and start your session. 5. [Onboard an enterprise customer](/sso/guides/onboard-enterprise-customers/): create their organization and give their IT admin the admin portal. 6. [Production readiness checklist](/sso/guides/launch-checklist/): what to check before your first customer goes live. ## Next [Section titled “Next”](#next) [Quickstart](/authenticate/sso/add-modular-sso/)Set up Scalekit and sign in a test user with SSO. [How Modular SSO works](/authenticate/sso/how-it-works/)The parts of an SSO login and how they fit together. --- # DOCUMENT BOUNDARY --- # Add Modular SCIM provisioning > Automate user provisioning with SCIM. Directory API and webhooks for real-time user data sync This guide shows you how to automate user provisioning with SCIM using Scalekit’s Directory API and webhooks. You’ll learn to sync user data in real-time, create webhook endpoints for instant updates, and build automated provisioning workflows that keep your application’s user data synchronized with your customers’ directory providers. With [SCIM Provisioning](/directory/guides/user-provisioning-basics) from Scalekit, you can: * Use **webhooks** to listen for events from your customers’ directory providers (e.g., user updates, group changes) * Use **REST APIs** to list users, groups, and directories on demand Scalekit abstracts the complexities of various directory providers, giving you a single interface to automate user lifecycle management. This enables you to create accounts for new hires during onboarding, deactivate accounts when employees depart, and adjust access levels as employees change roles. ![SCIM Quickstart](/.netlify/images?url=_astro%2Fscim-chart.D8FO-9f1.png\&w=5776\&h=1924\&dpl=6aedac7ec39c4cadbcd1959e) Using a coding agent?Copy SCIM prompt ## User provisioning with Scalekit’s directory API [Section titled “User provisioning with Scalekit’s directory API”](#user-provisioning-with-scalekits-directory-api) Scalekit’s directory API allows you to fetch information about users, groups, and directories associated with an organization on-demand. This approach is ideal for scheduled synchronization tasks, bulk data imports, or when you need to ensure your application’s user data matches the latest directory provider state. Let’s explore how to use the Directory API to retrieve user and group data programmatically. 1. ### Setting up the SDK [Section titled “Setting up the SDK”](#setting-up-the-sdk) Before you begin, ensure that your organization [has a directory set up in Scalekit](/guides/user-management/scim-provisioning/). Scalekit offers language-specific SDKs for fast SSO integration. Use the installation instructions below for your technology stack: * Node.js ```bash npm install @scalekit-sdk/node ``` * Python ```sh pip install scalekit-sdk-python ``` * Go ```sh go get -u github.com/scalekit-inc/scalekit-sdk-go/v2 ``` * Java The Java SDK is published to Scalekit’s Maven repository, `https://us-maven.pkg.dev/scalekit-public/java`. Add it to your build next to Maven Central. It needs no credentials. If your builds download dependencies only through a mirror such as Nexus or Artifactory, add this URL to the mirror instead. For Maven, add the `` and `` entries to the matching sections of your existing `pom.xml`. ```groovy // Gradle: build.gradle repositories { mavenCentral() maven { url "https://us-maven.pkg.dev/scalekit-public/java" } } dependencies { implementation "com.scalekit:scalekit-sdk-java:2.6.1" } ``` ```xml scalekit https://us-maven.pkg.dev/scalekit-public/java com.scalekit scalekit-sdk-java 2.6.1 ``` Navigate to **Dashboard > Developers > Settings > API Credentials** to obtain your credentials. Store your credentials securely in environment variables: .env ```shell # Get these values from Dashboard > Developers > Settings > API Credentials SCALEKIT_ENVIRONMENT_URL='https://b2b-app-dev.scalekit.com' SCALEKIT_CLIENT_ID='' SCALEKIT_CLIENT_SECRET='' ``` 2. ### Initialize the SDK and make your first API call [Section titled “Initialize the SDK and make your first API call”](#initialize-the-sdk-and-make-your-first-api-call) Initialize the Scalekit client with your environment variables and make your first API call to list organizations. * cURL Terminal ```bash # Security: Replace with a valid access token from Scalekit # This token authorizes your API requests to access organization data # Use case: Verify API connectivity and test authentication # Examples: Initial setup testing, debugging integration issues curl -L "https://$SCALEKIT_ENVIRONMENT_URL/api/v1/organizations?page_size=5" \ -H "Authorization: Bearer " ``` * Node.js Node.js ```javascript 1 import { ScalekitClient } from '@scalekit-sdk/node'; 2 3 // Initialize Scalekit client with environment variables 4 // Security: Always use environment variables for sensitive credentials 5 const scalekit = new ScalekitClient( 6 process.env.SCALEKIT_ENVIRONMENT_URL, 7 process.env.SCALEKIT_CLIENT_ID, 8 process.env.SCALEKIT_CLIENT_SECRET, 9 ); 10 11 try { 12 // Use case: Retrieve organizations for bulk user provisioning workflows 13 // Examples: Multi-tenant applications, enterprise customer onboarding 14 const { organizations } = await scalekit.organization.listOrganization({ 15 pageSize: 5, 16 }); 17 18 console.log(`Organization name: ${organizations[0].display_name}`); 19 console.log(`Organization ID: ${organizations[0].id}`); 20 } catch (error) { 21 console.error('Failed to list organizations:', error); 22 // Handle error appropriately for your application 23 } ``` * Python Python ```python 1 from scalekit import ScalekitClient 2 import os 3 4 # Initialize the SDK client with environment variables 5 # Security: Use os.getenv() to securely access credentials 6 scalekit_client = ScalekitClient( 7 env_url=os.getenv("SCALEKIT_ENVIRONMENT_URL"), 8 client_id=os.getenv("SCALEKIT_CLIENT_ID"), 9 client_secret=os.getenv("SCALEKIT_CLIENT_SECRET") 10 ) 11 12 try: 13 # Use case: Sync user data across multiple organizations 14 # Examples: Scheduled provisioning tasks, HR system integration 15 org_list = scalekit_client.organization.list_organizations(page_size=100) 16 17 if org_list: 18 print(f'Organization details: {org_list[0]}') 19 print(f'Organization ID: {org_list[0].id}') 20 except Exception as error: 21 print(f'Error listing organizations: {error}') 22 # Implement appropriate error handling for your use case ``` * Go Go ```go 1 package main 2 3 import ( 4 "context" 5 "fmt" 6 "os" 7 8 "github.com/scalekit/scalekit-go" 9 ) 10 11 // Initialize Scalekit client with environment variables 12 // Security: Always load credentials from environment, not hardcoded 13 scalekitClient := scalekit.NewScalekitClient( 14 os.Getenv("SCALEKIT_ENVIRONMENT_URL"), 15 os.Getenv("SCALEKIT_CLIENT_ID"), 16 os.Getenv("SCALEKIT_CLIENT_SECRET"), 17 ) 18 19 // Use case: Get specific organization for directory sync operations 20 // Examples: Targeted user provisioning, organization-specific workflows 21 organization, err := scalekitClient.Organization.GetOrganization( 22 ctx, 23 organizationId, 24 ) 25 if err != nil { 26 // Handle error appropriately for your application 27 return fmt.Errorf("failed to get organization: %w", err) 28 } ``` * Java Java ```java 1 import com.scalekit.ScalekitClient; 2 3 // Initialize Scalekit client with environment variables 4 // Security: Use System.getenv() to securely access credentials 5 ScalekitClient scalekitClient = new ScalekitClient( 6 System.getenv("SCALEKIT_ENVIRONMENT_URL"), 7 System.getenv("SCALEKIT_CLIENT_ID"), 8 System.getenv("SCALEKIT_CLIENT_SECRET") 9 ); 10 11 try { 12 // Use case: List organizations for automated provisioning workflows 13 // Examples: Enterprise customer setup, multi-tenant management 14 ListOrganizationsResponse organizations = scalekitClient.organizations() 15 .listOrganizations(5, ""); 16 17 if (!organizations.getOrganizations().isEmpty()) { 18 Organization firstOrg = organizations.getOrganizations().get(0); 19 System.out.println("Organization name: " + firstOrg.getDisplayName()); 20 System.out.println("Organization ID: " + firstOrg.getId()); 21 } 22 } catch (ScalekitException error) { 23 System.err.println("Failed to list organizations: " + error.getMessage()); 24 // Implement appropriate error handling 25 } ``` 3. ### Retrieve a directory [Section titled “Retrieve a directory”](#retrieve-a-directory) After successfully listing organizations, you’ll need to retrieve the specific directory to begin syncing user and group data. You can retrieve directories using either the organization and directory IDs, or fetch the primary directory for an organization. * Node.js Node.js ```javascript try { // Use case: Get specific directory when organization has multiple directories // Examples: Department-specific provisioning, multi-division companies const { directory } = await scalekit.directory.getDirectory('', ''); console.log(`Directory name: ${directory.name}`); // Use case: Get primary directory for simple provisioning workflows // Examples: Small organizations, single-directory setups const { directory } = await scalekit.directory.getPrimaryDirectoryByOrganizationId(''); console.log(`Primary directory ID: ${directory.id}`); } catch (error) { console.error('Failed to retrieve directory:', error); // Handle error appropriately for your application } ``` * Python Python ```python 1 try: 2 # Use case: Access specific directory for targeted user sync operations 3 # Examples: Regional offices, business unit-specific provisioning 4 directory = scalekit_client.directory.get_directory( 5 organization_id='', directory_id='' 6 ) 7 print(f'Directory name: {directory.name}') 8 9 # Use case: Get primary directory for streamlined user management 10 # Examples: Standard employee provisioning, main company directory 11 primary_directory = scalekit_client.directory.get_primary_directory_by_organization_id( 12 organization_id='' 13 ) 14 print(f'Primary directory ID: {primary_directory.id}') 15 except Exception as error: 16 print(f'Error retrieving directory: {error}') 17 # Implement appropriate error handling ``` * Go Go ```go // Use case: Retrieve specific directory for granular access control // Examples: Multi-tenant environments, department-level provisioning directory, err := scalekitClient.Directory().GetDirectory(ctx, organizationId, directoryId) if err != nil { return fmt.Errorf("failed to get directory: %w", err) } fmt.Printf("Directory name: %s\n", directory.Name) // Use case: Get primary directory for simplified user management // Examples: Automated provisioning workflows, bulk user imports directory, err := scalekitClient.Directory().GetPrimaryDirectoryByOrganizationId(ctx, organizationId) if err != nil { return fmt.Errorf("failed to get primary directory: %w", err) } fmt.Printf("Primary directory ID: %s\n", directory.ID) ``` * Java Java ```java 1 try { 2 // Use case: Access specific directory for detailed user management 3 // Examples: Custom provisioning logic, directory-specific rules 4 Directory directory = scalekitClient.directories() 5 .getDirectory("", ""); 6 System.out.println("Directory name: " + directory.getName()); 7 8 // Use case: Get primary directory for standard provisioning workflows 9 // Examples: Employee onboarding, automated user sync 10 Directory primaryDirectory = scalekitClient.directories() 11 .getPrimaryDirectoryByOrganizationId(""); 12 System.out.println("Primary directory ID: " + primaryDirectory.getId()); 13 } catch (ScalekitException error) { 14 System.err.println("Failed to retrieve directory: " + error.getMessage()); 15 // Implement appropriate error handling 16 } ``` 4. ### List users in a directory [Section titled “List users in a directory”](#list-users-in-a-directory) Once you have the directory information, you can fetch users within that directory. This is commonly used for bulk user synchronization and maintaining an up-to-date user database. * Node.js Node.js ```javascript try { // Use case: Bulk user synchronization and provisioning // Examples: New customer onboarding, scheduled user data sync const { users } = await scalekit.directory.listDirectoryUsers('', ''); // Process each user for provisioning or updates users.forEach(user => { console.log(`User email: ${user.email}, Name: ${user.name}`); // TODO: Implement your user provisioning logic here }); } catch (error) { console.error('Failed to list directory users:', error); // Handle error appropriately for your application } ``` * Python Python ```python try: # Use case: Automated user provisioning workflows # Examples: HR system integration, bulk user imports directory_users = scalekit_client.directory.list_directory_users( organization_id='', directory_id='' ) # Process each user for local database updates for user in directory_users: print(f'User email: {user.email}, Name: {user.name}') # TODO: Implement your user synchronization logic here except Exception as error: print(f'Error listing directory users: {error}') # Implement appropriate error handling ``` * Go Go ```go 1 // Configure pagination options for large user directories 2 options := &ListDirectoryUsersOptions{ 3 PageSize: 50, // Adjust based on your needs 4 PageToken: "", 5 } 6 7 // Use case: Paginated user retrieval for large directories 8 // Examples: Enterprise customer provisioning, regular sync jobs 9 directoryUsers, err := scalekitClient.Directory().ListDirectoryUsers(ctx, organizationId, directoryId, options) 10 if err != nil { 11 return fmt.Errorf("failed to list directory users: %w", err) 12 } 13 14 // Process each user 15 for _, user := range directoryUsers.Users { 16 fmt.Printf("User email: %s, Name: %s\n", user.Email, user.Name) 17 // TODO: Implement your user provisioning logic 18 } ``` * Java Java ```java 1 // Configure options for user listing with pagination 2 var options = ListDirectoryResourceOptions.builder() 3 .pageSize(50) // Adjust based on your requirements 4 .pageToken("") 5 .includeDetail(true) // Include detailed user information 6 .build(); 7 8 try { 9 // Use case: Enterprise user management and synchronization 10 // Examples: Scheduled sync tasks, user provisioning automation 11 ListDirectoryUsersResponse usersResponse = scalekitClient.directories() 12 .listDirectoryUsers(directory.getId(), organizationId, options); 13 14 // Process each user for provisioning 15 for (User user : usersResponse.getUsers()) { 16 System.out.println("User email: " + user.getEmail() + ", Name: " + user.getName()); 17 // TODO: Implement your user provisioning logic here 18 } 19 } catch (ScalekitException error) { 20 System.err.println("Failed to list directory users: " + error.getMessage()); 21 // Implement appropriate error handling 22 } ``` 5. ### List groups in a directory [Section titled “List groups in a directory”](#list-groups-in-a-directory) Groups are essential for implementing role-based access control (RBAC) in your application. After retrieving users, you can fetch groups to manage permissions and access levels based on organizational structure. * Node.js Node.js ```javascript 1 try { 2 // Use case: Role-based access control implementation 3 // Examples: Department-level permissions, project-based access 4 const { groups } = await scalekit.directory.listDirectoryGroups( 5 '', 6 '', 7 ); 8 9 // Process each group for RBAC setup 10 groups.forEach(group => { 11 console.log(`Group name: ${group.name}, ID: ${group.id}`); 12 // TODO: Implement your group-based permission logic here 13 }); 14 } catch (error) { 15 console.error('Failed to list directory groups:', error); 16 // Handle error appropriately for your application 17 } ``` * Python Python ```python try: # Use case: Department-based access control # Examples: Engineering vs Sales permissions, project team access directory_groups = scalekit_client.directory.list_directory_groups( directory_id='', organization_id='' ) # Process each group for permission mapping for group in directory_groups: print(f'Group name: {group.name}, ID: {group.id}') # TODO: Implement your group-based permission logic here except Exception as error: print(f'Error listing directory groups: {error}') # Implement appropriate error handling ``` * Go Go ```go 1 // Configure pagination for group listing 2 options := &ListDirectoryGroupsOptions{ 3 PageSize: 25, // Adjust based on expected group count 4 PageToken: "", 5 } 6 7 // Use case: Organizational role management 8 // Examples: Enterprise role hierarchy, department-based access 9 directoryGroups, err := scalekitClient.Directory().ListDirectoryGroups(ctx, organizationId, directoryId, options) 10 if err != nil { 11 return fmt.Errorf("failed to list directory groups: %w", err) 12 } 13 14 // Process each group for RBAC implementation 15 for _, group := range directoryGroups.Groups { 16 fmt.Printf("Group name: %s, ID: %s\n", group.Name, group.ID) 17 // TODO: Implement your group-based permission logic 18 } ``` * Java Java ```java 1 // Configure options for detailed group information 2 var options = ListDirectoryResourceOptions.builder() 3 .pageSize(25) // Adjust based on your requirements 4 .pageToken("") 5 .includeDetail(true) // Include group membership details 6 .build(); 7 8 try { 9 // Use case: Enterprise permission management 10 // Examples: Role assignments, access level configurations 11 ListDirectoryGroupsResponse groupsResponse = scalekitClient.directories() 12 .listDirectoryGroups(directory.getId(), organizationId, options); 13 14 // Process each group for permission mapping 15 for (Group group : groupsResponse.getGroups()) { 16 System.out.println("Group name: " + group.getName() + ", ID: " + group.getId()); 17 // TODO: Implement your group-based permission logic here 18 } 19 } catch (ScalekitException error) { 20 System.err.println("Failed to list directory groups: " + error.getMessage()); 21 // Implement appropriate error handling 22 } ``` Scalekit’s Directory API provides a simple way to fetch user and group information on-demand. Refer to our [API reference](https://docs.scalekit.com/apis/) to explore more capabilities. ## Realtime user provisioning with webhooks [Section titled “Realtime user provisioning with webhooks”](#realtime-user-provisioning-with-webhooks) While the Directory API is perfect for scheduled synchronization, webhooks enable immediate, real-time user provisioning. When directory providers send events to Scalekit, we forward them instantly to your application, allowing you to respond to user changes as they happen. This approach is ideal for scenarios requiring immediate action, such as new employee onboarding or emergency access revocation. 1. ### Create a secure webhook endpoint [Section titled “Create a secure webhook endpoint”](#create-a-secure-webhook-endpoint) Create a webhook endpoint to receive real-time events from directory providers. After implementing your endpoint, register it in **Dashboard > Webhooks** where you’ll receive a secret for payload verification. Critical security requirement Always verify webhook signatures before processing events. This prevents unauthorized parties from triggering your provisioning logic and protects against replay attacks. * Node.js Express.js ```javascript 1 app.post( 2 '/webhook', 3 express.raw({ type: 'application/json' }), 4 async (req, res) => { 5 const secret = process.env.SCALEKIT_WEBHOOK_SECRET 6 const payload = req.body.toString() 7 const headers = { 8 'webhook-id': req.headers['webhook-id'], 9 'webhook-timestamp': req.headers['webhook-timestamp'], 10 'webhook-signature': req.headers['webhook-signature'], 11 } 12 13 try { 14 scalekit.verifyWebhookPayload(secret, headers, payload) 15 } catch (error) { 16 console.error('Webhook signature verification failed:', error) 17 return res.status(401).json({ error: 'Invalid signature' }) 18 } 19 20 const event = JSON.parse(payload) 21 22 try { 23 const { email, name } = event.data 24 25 // Process the webhook event based on its type 26 switch (event.type) { 27 case 'organization.directory.user_created': 28 await createUserAccount(email, name); 29 break; 30 case 'organization.directory.user_updated': 31 await updateUserAccount(email, name); 32 break; 33 case 'organization.directory.user_deleted': 34 await deactivateUserAccount(email); 35 break; 36 default: 37 console.log(`Unhandled event type: ${event.type}`); 38 } 39 40 res.status(201).json({ message: 'Webhook processed successfully' }); 41 } catch (processingError) { 42 console.error('Failed to process webhook event:', processingError); 43 res.status(500).json({ error: 'Processing failed' }); 44 } 45 }); ``` * Python FastAPI ```python 1 from fastapi import FastAPI, Request, HTTPException 2 import os 3 import json 4 5 app = FastAPI() 6 7 @app.post("/webhook") 8 async def api_webhook(request: Request): 9 # Security: ALWAYS verify webhook signatures before processing events 10 # This prevents unauthorized webhook calls and replay attacks 11 12 raw_body = await request.body() 13 headers = { 14 "webhook-id": request.headers.get("webhook-id"), 15 "webhook-timestamp": request.headers.get("webhook-timestamp"), 16 "webhook-signature": request.headers.get("webhook-signature"), 17 } 18 19 try: 20 scalekit_client.verify_webhook_payload( 21 secret=os.getenv("SCALEKIT_WEBHOOK_SECRET"), 22 headers=headers, 23 payload=raw_body, 24 ) 25 except Exception as verification_error: 26 print(f"Webhook verification failed: {verification_error}") 27 raise HTTPException(status_code=401, detail="Webhook verification failed") 28 29 body = json.loads(raw_body.decode("utf-8")) 30 31 try: 32 event_type = body.get("type") 33 event_data = body.get("data", {}) 34 email = event_data.get("email") 35 name = event_data.get("name") 36 37 if event_type == "organization.directory.user_created": 38 await create_user_account(email, name) 39 elif event_type == "organization.directory.user_updated": 40 await update_user_account(email, name) 41 elif event_type == "organization.directory.user_deleted": 42 await deactivate_user_account(email) 43 44 return JSONResponse(status_code=201, content={"status": "processed"}) 45 46 except Exception as processing_error: 47 print(f"Failed to process webhook: {processing_error}") 48 raise HTTPException(status_code=500, detail="Event processing failed") ``` * Java Spring Boot ```java 1 @PostMapping("/webhook") 2 public ResponseEntity webhook( 3 @RequestBody String body, 4 @RequestHeader Map headers) { 5 6 // Security: ALWAYS verify webhook signatures before processing 7 // This prevents malicious webhook calls and protects against replay attacks 8 9 String secret = System.getenv("SCALEKIT_WEBHOOK_SECRET"); 10 11 Map verifyHeaders = new HashMap<>(); 12 verifyHeaders.put("webhook-id", headers.get("webhook-id")); 13 verifyHeaders.put("webhook-timestamp", headers.get("webhook-timestamp")); 14 verifyHeaders.put("webhook-signature", headers.get("webhook-signature")); 15 16 try { 17 // Java throws WebHookException. It does not return false. 18 scalekitClient.webhook() 19 .verifyWebhookPayload(secret, verifyHeaders, body.getBytes(java.nio.charset.StandardCharsets.UTF_8)); 20 } catch (Exception verificationError) { 21 System.err.println("Webhook verification failed: " + verificationError.getMessage()); 22 return ResponseEntity.badRequest().body("Webhook verification failed"); 23 } 24 25 try { 26 // Use case: Real-time user lifecycle management 27 // Examples: Employee onboarding, access termination, role modifications 28 ObjectMapper mapper = new ObjectMapper(); 29 JsonNode rootNode = mapper.readTree(body); 30 31 String eventType = rootNode.get("type").asText(); 32 JsonNode data = rootNode.get("data"); 33 34 switch (eventType) { 35 case "organization.directory.user_created": 36 String email = data.get("email").asText(); 37 String name = data.get("name").asText(); 38 createUserAccount(email, name); 39 break; 40 case "organization.directory.user_updated": 41 updateUserAccount(data); 42 break; 43 case "organization.directory.user_deleted": 44 deactivateUserAccount(data.get("email").asText()); 45 break; 46 default: 47 System.out.println("Unhandled event type: " + eventType); 48 } 49 50 return ResponseEntity.status(HttpStatus.CREATED).body("Webhook processed"); 51 52 } catch (Exception processingError) { 53 System.err.println("Failed to process webhook event: " + processingError.getMessage()); 54 return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR) 55 .body("Event processing failed"); 56 } 57 } ``` * Go Go ```go 1 // Security: Store webhook secret securely in environment variables 2 // Get this from Dashboard > Webhooks after registering your endpoint 3 webhookSecret := os.Getenv("SCALEKIT_WEBHOOK_SECRET") 4 5 http.HandleFunc("/webhook", func(w http.ResponseWriter, r *http.Request) { 6 // Security: ALWAYS verify webhook signatures before processing events 7 // This prevents unauthorized webhook calls and replay attacks 8 9 if r.Method != http.MethodPost { 10 http.Error(w, "Method not allowed", http.StatusMethodNotAllowed) 11 return 12 } 13 14 body, err := io.ReadAll(r.Body) 15 if err != nil { 16 http.Error(w, err.Error(), http.StatusBadRequest) 17 return 18 } 19 defer r.Body.Close() 20 21 // Extract webhook headers for verification 22 headers := map[string]string{ 23 "webhook-id": r.Header.Get("webhook-id"), 24 "webhook-signature": r.Header.Get("webhook-signature"), 25 "webhook-timestamp": r.Header.Get("webhook-timestamp"), 26 } 27 28 // Verify webhook signature to prevent malicious requests 29 valid, err := scalekitClient.VerifyWebhookPayload(webhookSecret, headers, body) 30 if err != nil || !valid { 31 http.Error(w, "Invalid webhook signature", http.StatusUnauthorized) 32 return 33 } 34 35 // Use case: Instant user provisioning and lifecycle management 36 // Examples: Real-time onboarding, emergency access revocation, role synchronization 37 var webhookEvent WebhookEvent 38 if err := json.Unmarshal(body, &webhookEvent); err != nil { 39 http.Error(w, "Invalid webhook payload", http.StatusBadRequest) 40 return 41 } 42 43 switch webhookEvent.Type { 44 case "organization.directory.user_created": 45 err = createUserAccount(webhookEvent.Data.Email, webhookEvent.Data.Name) 46 case "organization.directory.user_updated": 47 err = updateUserAccount(webhookEvent.Data) 48 case "organization.directory.user_deleted": 49 err = deactivateUserAccount(webhookEvent.Data.Email) 50 default: 51 fmt.Printf("Unhandled event type: %s\n", webhookEvent.Type) 52 } 53 54 if err != nil { 55 http.Error(w, "Failed to process webhook", http.StatusInternalServerError) 56 return 57 } 58 59 w.WriteHeader(http.StatusCreated) 60 w.Write([]byte(`{"status": "processed"}`)) 61 }) ``` 2. ### Register your webhook endpoint [Section titled “Register your webhook endpoint”](#register-your-webhook-endpoint) After implementing your secure webhook endpoint, register it in the Scalekit dashboard to start receiving events: 1. Navigate to **Dashboard > Webhooks** 2. Click **+Add Endpoint** 3. Enter your webhook endpoint URL (e.g., `https://your-app.com/api/webhooks/scalekit`) 4. Add a meaningful description for your reference 5. Select the event types you want to receive. Common choices include: * `organization.directory.user_created` - New user provisioning * `organization.directory.user_updated` - User profile changes * `organization.directory.user_deleted` - User deactivated or deleted * `organization.directory.group_created` - New group creation * `organization.directory.group_updated` - Group modifications Once registered, your webhook endpoint will start receiving event payloads from directory providers in real-time. 3. ### Process webhook events [Section titled “Process webhook events”](#process-webhook-events) Scalekit standardizes event payloads across different directory providers, ensuring consistent data structure regardless of whether your customers use Azure AD, Okta, Google Workspace, or other providers. When directory changes occur, Scalekit sends events with the following structure. This example is shortened. See [Directory events](/directory/reference/directory-events/) for every field and event. Webhook event payload ```json 1 { 2 "spec_version": "1", 3 "id": "evt_53891546994442316", 4 "type": "organization.directory.user_created", 5 "occurred_at": "2025-01-06T18:44:25.153954Z", 6 "environment_id": "env_53814739859406915", 7 "organization_id": "org_53879494091473415", 8 "object": "DirectoryUser", 9 "data": { 10 "active": true, 11 "dp_id": "00u1a2b3c4d5e6f7g8h9", 12 "email": "john.doe@acmecorp.com", 13 "groups": [ 14 { 15 "id": "dirgroup_53891546960887900", 16 "name": "Engineering" 17 } 18 ], 19 "id": "diruser_53891546960887884", 20 "name": "John Doe", 21 "organization_id": "org_53879494091473415", 22 "preferred_username": "john.doe@acmecorp.com" 23 } 24 } ``` You have now successfully implemented and registered a webhook endpoint, enabling your application to receive real-time events for automated user provisioning. Your system can now respond instantly to directory changes, providing seamless user lifecycle management. Refer to our [webhook implementation guide](/authenticate/implement-workflows/implement-webhooks/) for the complete list of available event types and payload structures. --- # DOCUMENT BOUNDARY --- # Add users to organizations > Ways in which users join or get added to organizations The journey of a user into your application begins with how they join an organization. A smooth onboarding experience sets the tone for their entire interaction with your product, while administrators need flexible options to manage their organization members. Scalekit supports a variety of ways for users to join organizations. This guide covers methods ranging from manual additions in the dashboard to fully automated provisioning. ## Enable user invitations through your app [Section titled “Enable user invitations through your app”](#enable-user-invitations-through-your-app) Scalekit lets you add user invitation features to your app, allowing users to invite others to join their organization. 1. #### Begin the invite flow [Section titled “Begin the invite flow”](#begin-the-invite-flow) When a user clicks the invite button in your application, retrieve the `organization_id` from their ID token or the application’s context. Then, call the Scalekit SDK with the invitee’s email address to send the invitation. * Node.js Express.js invitation API ```javascript 1 // POST /api/organizations/:orgId/invite 2 app.post('/api/organizations/:orgId/invite', async (req, res) => { 3 const { orgId } = req.params 4 const { email } = req.body 5 6 try { 7 // Create user and add to organization with invitation 8 const { user } = await scalekit.user.createUserAndMembership(orgId, { 9 email, 10 sendInvitationEmail: true, // Scalekit sends the invitation email 11 }) 12 13 res.json({ 14 message: 'Invitation sent successfully', 15 userId: user.id, 16 email: user.email 17 }) 18 } catch (error) { 19 res.status(400).json({ error: error.message }) 20 } 21 }) ``` * Python Django invitation API ```python 1 # Python - Django invitation API 2 @api_view(['POST']) 3 def invite_user_to_organization(request, org_id): 4 email = request.data.get('email') 5 6 try: 7 # Create user and add to organization with invitation 8 user_response = scalekit_client.user.create_user_and_membership(org_id, { 9 'email': email, 10 'send_invitation_email': True, # Scalekit sends the invitation email 11 }) 12 13 return JsonResponse({ 14 'message': 'Invitation sent successfully', 15 'user_id': user_response['user']['id'], 16 'email': user_response['user']['email'] 17 }) 18 except Exception as error: 19 return JsonResponse({'error': str(error)}, status=400) ``` * Go Gin invitation API ```go 1 // Go - Gin invitation API 2 func inviteUserToOrganization(c *gin.Context) { 3 orgID := c.Param("orgId") 4 5 var req struct { 6 Email string `json:"email"` 7 } 8 9 if err := c.ShouldBindJSON(&req); err != nil { 10 c.JSON(400, gin.H{"error": err.Error()}) 11 return 12 } 13 14 // Create user and add to organization with invitation 15 userResp, err := scalekitClient.User.CreateUserAndMembership(ctx, orgID, scalekit.CreateUserAndMembershipRequest{ 16 Email: req.Email, 17 SendInvitationEmail: scalekit.Bool(true), // Scalekit sends the invitation email 18 }) 19 20 if err != nil { 21 c.JSON(400, gin.H{"error": err.Error()}) 22 return 23 } 24 25 c.JSON(200, gin.H{ 26 "message": "Invitation sent successfully", 27 "user_id": userResp.User.Id, 28 "email": userResp.User.Email, 29 }) 30 } ``` * Java Spring Boot invitation API ```java 1 // Java - Spring Boot invitation API 2 @PostMapping("/api/organizations/{orgId}/invite") 3 public ResponseEntity> inviteUserToOrganization( 4 @PathVariable String orgId, 5 @RequestBody InviteRequest request, 6 HttpSession session 7 ) { 8 try { 9 // Create user and add to organization with invitation 10 CreateUser createUser = CreateUser.newBuilder() 11 .setEmail(request.email()) 12 .setSendInvitationEmail(true) // Scalekit sends the invitation email 13 .build(); 14 15 CreateUserAndMembershipResponse response = scalekitClient.users() 16 .createUserAndMembership(orgId, createUser); 17 18 return ResponseEntity.ok(Map.of( 19 "message", "Invitation sent successfully", 20 "user_id", response.getUser().getId(), 21 "email", response.getUser().getEmail() 22 )); 23 } catch (Exception error) { 24 return ResponseEntity.badRequest().body( 25 Map.of("error", error.getMessage()) 26 ); 27 } 28 } ``` This sends a email invitation to invitee to join the organization. 2. #### Set up initiate login endpoint [Section titled “Set up initiate login endpoint”](#set-up-initiate-login-endpoint) After the invitee clicks the invitation link they receive via email, Scalekit will handle verifying their identity in the background through the unique link embedded. Once verified, Scalekit automatically tries to log the invitee into your application by redirecting them to your app’s [configured initiate login endpoint](/guides/dashboard/intitate-login-endpoint/). Let’s go ahead and implement this endpoint. * Node.js routes/auth.js ```javascript // Handle indirect auth entry points app.get('/login', (req, res) => { const redirectUri = 'http://localhost:3000/auth/callback'; const options = { scopes: ['openid', 'profile', 'email', 'offline_access'] }; const authorizationUrl = scalekit.getAuthorizationUrl(redirectUri, options); res.redirect(authorizationUrl); }); ``` * Python routes/auth.py ```python from flask import redirect from scalekit import AuthorizationUrlOptions # Handle indirect auth entry points @app.route('/login') def login(): redirect_uri = 'http://localhost:3000/auth/callback' options = AuthorizationUrlOptions() options.scopes = ['openid', 'profile', 'email', 'offline_access'] options.state = session['oauth_state'] authorization_url = scalekit_client.get_authorization_url(redirect_uri, options) return redirect(authorization_url) ``` * Go routes/auth.go ```go // Handle indirect auth entry points r.GET("/login", func(c *gin.Context) { redirectUri := "http://localhost:3000/auth/callback" options := scalekitClient.AuthorizationUrlOptions{ Scopes: []string{"openid", "profile", "email", "offline_access"} } authorizationUrl, _ := scalekitClient.GetAuthorizationUrl(redirectUri, options) c.Redirect(http.StatusFound, authorizationUrl.String()) }) ``` * Java AuthController.java ```java import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RestController; import java.net.URL; // Handle indirect auth entry points @GetMapping("/login") public String login() { String redirectUri = "http://localhost:3000/auth/callback"; AuthorizationUrlOptions options = new AuthorizationUrlOptions(); options.setScopes(Arrays.asList("openid", "profile", "email", "offline_access")); URL authorizationUrl = scalekitClient.authentication().getAuthorizationUrl(redirectUri, options); return "redirect:" + authorizationUrl.toString(); } ``` This redirection ensures that the invitee is logged into your application after they accept the invitation. User won’t see a login page along the way since the identity is already verified through the unique link embedded in the invitation email. If you use a `PRE_SESSION_CREATION` interceptor, it also runs on this first login, so the invitee’s access token includes your custom claims. See [Pre-session creation](/authenticate/interceptors/auth-flow-interceptors/#pre-session-creation). The user will get an invitation email from Scalekit to accept the invitation. ## Enable Just-In-Time (JIT) provisioning [Section titled “Enable Just-In-Time (JIT) provisioning”](#enable-just-in-time-jit-provisioning) Organization administrators, especially at enterprises, prefer to have users verify their identity through their preferred identity provider (such as Okta, Microsoft Entra ID, etc.). This is particularly useful for enterprises with many users who need to ensure that only organization members can access the application. Scalekit will provision the user accounts in your app automatically when they sign in through SSO for the first time and map the user to the same organization. [Learn more](/authenticate/manage-users-orgs/jit-provisioning/) ## Enable SCIM provisioning [Section titled “Enable SCIM provisioning”](#enable-scim-provisioning) Enterprises often rely on user directory providers (such as Okta, Microsoft Entra ID, etc.) to handle user management. This enables their organization administrators to control and manage access for organization members efficiently. Scalekit supports SCIM provisioning, allowing your app to connect with these user directory providers so that user accounts are automatically created or removed in your app when users join or leave the organization. This automation is especially valuable for enterprise customers who want to ensure their licenses or seats are allocated efficiently, with organization admins managing access based on user groups. [Learn more](/authenticate/manage-users-orgs/scim-provisioning/) ## Add users through dashboard [Section titled “Add users through dashboard”](#add-users-through-dashboard) For administrative or support purposes, the Scalekit dashboard allows you to add new members directly to a customer’s organization 1. In the Scalekit dashboard, navigate to **Dashboard > Organizations**. 2. Select the organization you want to add a user to. 3. Go to the **Users** tab and click Invite User. 4. Fill out the invitation form: * Email Address: The user’s email * Role: Assign a role from the dropdown (e.g., Admin, Member, or a custom organization role) * Personal Information (Optional): Add the user’s first name, last name, and display name 5. Click **Send Invitation** The user will receive an email with a link to accept the invitation and join your organization. Once they accept, their status will update in the Users tab. --- # DOCUMENT BOUNDARY --- # Organization session policy > Override application-level session timeouts for specific organizations with custom absolute and idle session policies By default, all organizations inherit the session policy configured at the application level — covering absolute session duration and idle timeout. When an enterprise customer requires stricter or different session controls than your application defaults, you can set a custom session policy on a per-organization basis. Scalekit always enforces the **stricter of the two** (application vs. organization) at session creation time, so organization policies can only tighten — not relax — your application-level defaults. ## How it works [Section titled “How it works”](#how-it-works) Each organization can either inherit the application session policy or define its own. The two settings you can customize per organization are: | Setting | Behavior | | ---------------------------- | --------------------------------------------------------------------------------------------------------------------------------------- | | **Absolute session timeout** | Maximum session lifetime regardless of activity. Scalekit applies `min(app value, org value)`. | | **Idle session timeout** | Inactivity period after which the session expires. Enabled if either the app or org has it on; duration is `min(app value, org value)`. | **Access token lifetime** is not configurable at the org level. It remains an application-level setting only. ## Set up custom session policy for an organization [Section titled “Set up custom session policy for an organization”](#set-up-custom-session-policy-for-an-organization) ### Prerequisites [Section titled “Prerequisites”](#prerequisites) Enable the **Session Policy** feature for an organization before configuring a custom policy. Navigate to **Dashboard > Organizations > \[Organization] > Overview > Edit** and turn on **Session Policy** feature. You can also use the [organization settings API](/apis/#tag/organizations/PATCH/api/v1/organizations/%7Bid%7D/settings). ![Enable session policy feature for organization.](/.netlify/images?url=_astro%2F2026-05-21-16-43-01.CaYNvMBM.png\&w=2920\&h=1570\&dpl=6aedac7ec39c4cadbcd1959e) ### Configure via dashboard [Section titled “Configure via dashboard”](#configure-via-dashboard) Once the **Session Policy** feature is enabled for the organization, you can configure a custom policy for the organization via the Scalekit dashboard. 1. Go to **Dashboard > Organizations** and open the organization. 2. Click the **Session Policy** tab. 3. Select **Custom** to apply org-specific settings, or **Application** to revert to defaults. 4. Set the **Absolute session timeout** and **Idle session timeout** for the organization. 5. Click **Save**. ![Edit session policy for the organization.](/.netlify/images?url=_astro%2Forganization-session-policy.CyEzWmK_.png\&w=2930\&h=1584\&dpl=6aedac7ec39c4cadbcd1959e) ### Let org admins self-serve via Hosted Widgets [Section titled “Let org admins self-serve via Hosted Widgets”](#let-org-admins-self-serve-via-hosted-widgets) You can let your customers manage their own session policy through [Hosted Widgets](/authenticate/manage-users-orgs/hosted-widgets/) — an embeddable self-service portal that lets your customers manage organization and user-level settings. When the `Session Policy` feature is enabled for an organization, the Session Policy widget becomes available in the Hosted Widget portal. ### Configure via API/SDK [Section titled “Configure via API/SDK”](#configure-via-apisdk) 1. **Get the current session policy** Retrieve the active session policy for an organization to display it in your settings UI or audit the current configuration. * Node.js Get session policy ```javascript try { const policy = await scalekit.organization.getOrganizationSessionPolicy('org_12345'); // policySource: 1 = APPLICATION (inheriting defaults), 2 = CUSTOM (org-specific values active) console.log('Policy source:', policy.policySource); console.log('Absolute timeout (minutes):', policy.absoluteSessionTimeout); console.log('Idle timeout enabled:', policy.idleSessionTimeoutEnabled); } catch (error) { console.error('Failed to get session policy:', error.message); } ``` * Python Get session policy ```python from scalekit.v1.organizations.organizations_pb2 import SessionPolicyType try: response, _ = scalekit_client.organization.get_organization_session_policy('org_12345') policy = response.policy if policy.policy_source == SessionPolicyType.CUSTOM: print('Absolute timeout (minutes):', policy.absolute_session_timeout.value) print('Idle timeout enabled:', policy.idle_session_timeout_enabled.value) except Exception as e: print('Failed to get session policy:', e) ``` * Go Get session policy ```go policy, err := scalekitClient.Organization().GetOrganizationSessionPolicy(ctx, "org_12345") if err != nil { log.Fatal(err) } if policy.PolicySource == scalekit.SessionPolicySourceCustom { fmt.Println("Absolute timeout (minutes):", policy.AbsoluteSessionTimeout.GetValue()) fmt.Println("Idle timeout enabled:", policy.IdleSessionTimeoutEnabled.GetValue()) } ``` * Java Get session policy ```java import com.scalekit.grpc.scalekit.v1.organizations.OrganizationSessionPolicySettings; import com.scalekit.grpc.scalekit.v1.organizations.SessionPolicyType; try { OrganizationSessionPolicySettings policy = scalekitClient.organizations().getOrganizationSessionPolicy("org_12345"); if (policy.getPolicySource() == SessionPolicyType.CUSTOM) { System.out.println("Absolute timeout (minutes): " + policy.getAbsoluteSessionTimeout().getValue()); System.out.println("Idle timeout enabled: " + policy.getIdleSessionTimeoutEnabled().getValue()); } } catch (Exception e) { System.err.println("Failed to get session policy: " + e.getMessage()); } ``` 2. **Set a custom session policy** Apply a custom policy when an organization requires different session durations than your application defaults. * Node.js Set custom session policy ```javascript try { const updated = await scalekit.organization.updateOrganizationSessionPolicy('org_12345', { policySource: 'CUSTOM', absoluteSessionTimeout: 480, absoluteSessionTimeoutUnit: 'MINUTES', idleSessionTimeoutEnabled: true, idleSessionTimeout: 60, idleSessionTimeoutUnit: 'MINUTES', }); console.log('Policy updated:', updated.policySource); } catch (error) { console.error('Failed to update session policy:', error.message); } ``` * Python Set custom session policy ```python 1 from scalekit.v1.organizations.organizations_pb2 import SessionPolicyType 2 from scalekit.v1.commons.commons_pb2 import TimeUnit 3 4 try: 5 response, _ = scalekit_client.organization.update_organization_session_policy( 6 organization_id='org_12345', 7 policy_source=SessionPolicyType.CUSTOM, 8 absolute_session_timeout=480, 9 absolute_session_timeout_unit=TimeUnit.MINUTES, 10 idle_session_timeout_enabled=True, 11 idle_session_timeout=60, 12 idle_session_timeout_unit=TimeUnit.MINUTES, 13 ) 14 15 print('Policy updated:', response.policy.policy_source) 16 except Exception as e: 17 print('Failed to update session policy:', e) ``` * Go Set custom session policy ```go 1 timeout := int32(480) 2 idleTimeout := int32(60) 3 idleEnabled := true 4 5 updated, err := scalekitClient.Organization().UpdateOrganizationSessionPolicy(ctx, "org_12345", scalekit.OrganizationSessionPolicy{ 6 PolicySource: scalekit.SessionPolicySourceCustom, 7 AbsoluteSessionTimeout: &timeout, 8 AbsoluteSessionTimeoutUnit: scalekit.TimeUnitMinutes, 9 IdleSessionTimeoutEnabled: &idleEnabled, 10 IdleSessionTimeout: &idleTimeout, 11 IdleSessionTimeoutUnit: scalekit.TimeUnitMinutes, 12 }) 13 if err != nil { 14 log.Fatal(err) 15 } 16 17 fmt.Println("Policy updated:", updated.PolicySource) ``` * Java Set custom session policy ```java 1 import com.google.protobuf.Int32Value; 2 import com.google.protobuf.BoolValue; 3 import com.scalekit.grpc.scalekit.v1.commons.TimeUnit; 4 import com.scalekit.grpc.scalekit.v1.organizations.OrganizationSessionPolicySettings; 5 import com.scalekit.grpc.scalekit.v1.organizations.SessionPolicyType; 6 7 try { 8 OrganizationSessionPolicySettings policy = OrganizationSessionPolicySettings.newBuilder() 9 .setPolicySource(SessionPolicyType.CUSTOM) 10 .setAbsoluteSessionTimeout(Int32Value.of(480)) 11 .setAbsoluteSessionTimeoutUnit(TimeUnit.MINUTES) 12 .setIdleSessionTimeoutEnabled(BoolValue.of(true)) 13 .setIdleSessionTimeout(Int32Value.of(60)) 14 .setIdleSessionTimeoutUnit(TimeUnit.MINUTES) 15 .build(); 16 17 OrganizationSessionPolicySettings updated = 18 scalekitClient.organizations().updateOrganizationSessionPolicy("org_12345", policy); 19 20 System.out.println("Policy updated: " + updated.getPolicySource()); 21 } catch (Exception e) { 22 System.err.println("Failed to update session policy: " + e.getMessage()); 23 } ``` 3. **Revert to application defaults** Remove the custom policy and restore the organization to the application-level session settings. * Node.js Revert to application defaults ```javascript try { await scalekit.organization.updateOrganizationSessionPolicy('org_12345', { policySource: 'APPLICATION', }); } catch (error) { console.error('Failed to revert session policy:', error.message); } ``` * Python Revert to application defaults ```python from scalekit.v1.organizations.organizations_pb2 import SessionPolicyType try: scalekit_client.organization.update_organization_session_policy( organization_id='org_12345', policy_source=SessionPolicyType.APPLICATION, ) except Exception as e: print('Failed to revert session policy:', e) ``` * Go Revert to application defaults ```go _, err := scalekitClient.Organization().UpdateOrganizationSessionPolicy(ctx, "org_12345", scalekit.OrganizationSessionPolicy{ PolicySource: scalekit.SessionPolicySourceApplication, }) if err != nil { log.Fatal(err) } ``` * Java Revert to application defaults ```java import com.scalekit.grpc.scalekit.v1.organizations.OrganizationSessionPolicySettings; import com.scalekit.grpc.scalekit.v1.organizations.SessionPolicyType; try { OrganizationSessionPolicySettings policy = OrganizationSessionPolicySettings.newBuilder() .setPolicySource(SessionPolicyType.APPLICATION) .build(); scalekitClient.organizations().updateOrganizationSessionPolicy("org_12345", policy); } catch (Exception e) { System.err.println("Failed to revert session policy: " + e.getMessage()); } ``` --- # DOCUMENT BOUNDARY --- # Remove users from organizations > Remove users from organizations through dashboard management and API while maintaining security and compliance As your application grows and teams evolve, your administrators will need to manage user access when employees leave, change roles, or when administrators need to revoke access for security reasons. Proper user removal ensures that access control remains accurate, licenses are managed efficiently, and security is maintained across your organization. When a user is removed from an organization, they immediately lose access to that organization’s resources. The user’s account remains in Scalekit, but their membership status changes, and they can no longer access organization-specific data or features. * User loses access to ONE specific organization * User account remains in Scalekit * User can still access OTHER organizations they belong to * Reversible - user can be re-added later - Node.js Remove users from organizations ```javascript // Use case: Remove user during offboarding workflow triggered by HR system await scalekit.user.deleteMembership({ organizationId: 'org_12345', userId: 'usr_67890' }) ``` - Python Remove users from organizations ```python # Use case: Remove user during offboarding workflow triggered by HR system scalekit_client.users.delete_membership( organization_id="org_12345", user_id="usr_67890" ) ``` - Go Remove users from organizations ```go // Use case: Remove user during offboarding workflow triggered by HR system err := scalekitClient.User().DeleteMembership(ctx, "org_123", "user_456", false) if err != nil { log.Printf("Failed to remove user: %v", err) return err } ``` - Java Remove users from organizations ```java // Use case: Remove user during offboarding workflow triggered by HR system try { scalekitClient.user().deleteMembership("org_123", "user_456"); } catch (Exception e) { log.error("Failed to remove user: " + e.getMessage()); throw e; } ``` The membership is removed, effectively dropping the user’s access to the specified organization. ```diff 1 { 2 "user": { 3 "id": "usr_96194455173857548", 4 "environment_id": "env_58345499215790610", 5 "create_time": "2025-10-25T14:46:03.300Z", 6 "update_time": "2025-10-31T11:33:31.639425Z", 7 "email": "saifshine7+locksmith@gmail.com", 8 "external_id": "hitman", 9 "memberships": [ 10 { 11 "organization_id": "org_96194455157080332", 12 "membership_status": "ACTIVE", 13 "roles": [ 14 { 15 "id": "role_69229687729029148", 16 "name": "admin", 17 "display_name": "Admin" 18 } 19 ], 20 "name": "", 21 "metadata": {}, 22 "display_name": "" 23 }, 24 - { 25 "organization_id": "org_67609586521080405", 26 "membership_status": "PENDING_INVITE", 27 "roles": [ 28 - { 29 "id": "role_69229700009951260", 30 "name": "member", 31 "display_name": "Member" 32 - } 33 - ], 34 "name": "Megasoft Inc", 35 "metadata": {}, 36 "display_name": "Megasoft Inc", 37 "created_at": "2025-10-31T12:38:42.270Z", 38 "expires_at": "2025-11-15T12:38:42.231316Z" 39 - } 40 ], 41 "user_profile": { 42 "id": "usp_96194455173923084", 43 "first_name": "Saif", 44 "last_name": "Shines", 45 "name": "", 46 "locale": "", 47 "email_verified": true, 48 "phone_number": "80384873", 49 "metadata": {}, 50 "custom_attributes": {} 51 }, 52 "metadata": {} 53 } 54 } ``` User removal from an organization involves several important considerations and behaviors. * When a user is removed from an organization and has no other organizational memberships, Scalekit will automatically delete their user account. * Your application is responsible for handling the transfer or deletion of the user’s resources when they are removed from an organization. * Scalekit immediately terminates the user’s active session upon removal from an organization. * Removing a user from one organization does not impact their memberships in other organizations. * When a user is removed from an organization, that organization will be automatically removed from the user’s organization switcher options. ## Automate user removal with directory sync [Section titled “Automate user removal with directory sync”](#automate-user-removal-with-directory-sync) When organizations use enterprise directory providers with [SCIM provisioning](/guides/user-management/scim-provisioning/), users are automatically removed from Scalekit organizations when they’re deprovisioned in the source directory. This ensures consistent access control across all systems without requiring manual intervention. When a user is removed from your enterprise directory provider (such as Okta, Azure AD, or JumpCloud): 1. The directory provider sends a SCIM DELETE request to Scalekit 2. Scalekit automatically removes the user’s membership from the organization by marking the `memberships.membership_status` as `INACTIVE` 3. The user immediately loses access to organization resources 4. Your application receives webhook notifications about the membership change This automation is particularly valuable for enterprise customers who manage large numbers of users and need to ensure that license allocation and access control remain synchronized with their directory provider. ## Remove users in the Scalekit dashboard [Section titled “Remove users in the Scalekit dashboard”](#remove-users-in-the-scalekit-dashboard) Use the Scalekit dashboard when administrators need to manually remove users for compliance, security, support or administrative purposes. This approach provides direct control and visibility into the removal process, making it ideal for situations requiring manual oversight. 1. Sign in to the Scalekit dashboard and navigate to **Dashboard** > **Organizations**. Select the organization from which you want to remove users. 2. Click on the **Users** tab to view all organization members. Locate the user you want to remove from the user list. You can use the search functionality to quickly find specific users by name or email. 3. Click the **Actions** menu (three dots) next to the user’s name and select **Remove from organization**. A confirmation dialog will appear to prevent accidental removals. 4. Review the confirmation dialog to ensure you’re removing the correct user. Click **Remove user** to confirm. The user will immediately lose access to the organization and its resources. --- # DOCUMENT BOUNDARY --- # Add Modular SSO > Add enterprise SSO to an app that keeps its own login: set up Scalekit, send a user to their identity provider and read their profile at your callback. This quickstart adds enterprise single sign-on (SSO) to an app that keeps its own users and sessions. By the end, a test user signs in through the SSO simulator and your app reads their profile at its callback URL. New to Modular SSO? Start with [What is Modular SSO](/authenticate/sso/overview/). Your app signs users in with Auth0, Amazon Cognito, Firebase or Supabase? Follow that system’s guide instead; see [Choose how to integrate](/authenticate/sso/choose-integration/). Want Scalekit to run the whole login? Use the [Full Stack Auth quickstart](/authenticate/fsa/quickstart/). Using a coding agent?Copy SSO prompt ## Before you start [Section titled “Before you start”](#before-you-start) * A Scalekit account. Use your development environment: it comes with a test organization and the SSO simulator. * A web app whose backend can run the Node.js, Python, Go or Java SDK. 1. ## Switch the environment to Modular Auth mode [Section titled “Switch the environment to Modular Auth mode”](#switch-the-environment-to-modular-auth-mode) In the Scalekit dashboard, go to **Settings** > **Authentication Mode**, select **Modular Auth** and select **Save**. In this mode your app keeps its users and sessions, and Scalekit returns the verified user to your app. 2. ## Set up Scalekit [Section titled “Set up Scalekit”](#set-up-scalekit) Install the SDK for your stack. * Node.js ```bash npm install @scalekit-sdk/node ``` * Python ```sh pip install scalekit-sdk-python ``` * Go ```sh go get -u github.com/scalekit-inc/scalekit-sdk-go/v2 ``` * Java The Java SDK is published to Scalekit’s Maven repository, `https://us-maven.pkg.dev/scalekit-public/java`. Add it to your build next to Maven Central. It needs no credentials. If your builds download dependencies only through a mirror such as Nexus or Artifactory, add this URL to the mirror instead. For Maven, add the `` and `` entries to the matching sections of your existing `pom.xml`. ```groovy // Gradle: build.gradle repositories { mavenCentral() maven { url "https://us-maven.pkg.dev/scalekit-public/java" } } dependencies { implementation "com.scalekit:scalekit-sdk-java:2.6.1" } ``` ```xml scalekit https://us-maven.pkg.dev/scalekit-public/java com.scalekit scalekit-sdk-java 2.6.1 ``` Copy your API credentials from **Developers** > **Settings** > **API Credentials** into your `.env` file: .env ```sh SCALEKIT_ENVIRONMENT_URL= # Example: https://acme.scalekit.dev or https://auth.acme.com (if custom domain is set) SCALEKIT_CLIENT_ID= # Example: skc_1234567890abcdef SCALEKIT_CLIENT_SECRET= # Example: test_abcdef1234567890 ``` 3. ## Register your callback URL [Section titled “Register your callback URL”](#register-your-callback-url) Scalekit sends users back to your app only at URLs you register. Go to **Authentication** > **Redirect URLs** and add `http://localhost:3000/auth/callback` under **Allowed callback URLs**. In production, add your app’s own callback URL. See [Register redirect URLs](/authenticate/sso/redirect-urls/). 4. ## Send the user to their identity provider [Section titled “Send the user to their identity provider”](#send-the-user-to-their-identity-provider) Build an authorization URL with the SDK and redirect the user to it. The URL names your callback URL and the user’s organization. To try it now, use the ID of your test organization, under **Organizations** in the dashboard. * Node.js authorization-url.js ```javascript 1 import { ScalekitClient } from '@scalekit-sdk/node'; 2 3 const scalekit = new ScalekitClient( 4 '', // Your Scalekit environment URL 5 '', // Unique identifier for your app 6 '', 7 ); 8 9 const options = {}; 10 11 // Send the user to their organization's SSO. To route by connection ID or by 12 // the user's email domain instead, see /sso/guides/authorization-url/ 13 options['organizationId'] = 'org_15421144869927830'; 14 15 // redirect_uri: Your callback endpoint that receives the authorization code 16 // Must match the URL registered in your Scalekit dashboard 17 const redirectUrl = 'http://localhost:3000/auth/callback'; 18 19 const authorizationURL = scalekit.getAuthorizationUrl(redirectUrl, options); 20 // Redirect user to this URL to begin SSO authentication ``` * Python authorization_url.py ```python 1 from scalekit import ScalekitClient, AuthorizationUrlOptions 2 3 scalekit_client = ScalekitClient( 4 '', # Your Scalekit environment URL 5 '', # Unique identifier for your app 6 '' 7 ) 8 9 options = AuthorizationUrlOptions() 10 11 # Send the user to their organization's SSO. To route by connection ID or by 12 # the user's email domain instead, see /sso/guides/authorization-url/ 13 options.organization_id = 'org_15421144869927830' 14 15 # redirect_uri: Your callback endpoint that receives the authorization code 16 # Must match the URL registered in your Scalekit dashboard 17 redirect_uri = 'http://localhost:3000/auth/callback' 18 19 authorization_url = scalekit_client.get_authorization_url( 20 redirect_uri=redirect_uri, 21 options=options 22 ) 23 # Redirect user to this URL to begin SSO authentication ``` * Go authorization_url.go ```go 1 package main 2 3 import ( 4 "fmt" 5 "log" 6 7 scalekit "github.com/scalekit-inc/scalekit-sdk-go/v2" 8 ) 9 10 func main() { 11 scalekitClient := scalekit.NewScalekitClient( 12 "", // Your Scalekit environment URL 13 "", // Unique identifier for your app 14 "", 15 ) 16 17 options := scalekit.AuthorizationUrlOptions{} 18 19 // Send the user to their organization's SSO. To route by connection ID or by 20 // the user's email domain instead, see /sso/guides/authorization-url/ 21 options.OrganizationId = "org_15421144869927830" 22 23 // redirectUrl: Your callback endpoint that receives the authorization code 24 // Must match the URL registered in your Scalekit dashboard 25 redirectUrl := "http://localhost:3000/auth/callback" 26 27 authorizationURL, err := scalekitClient.GetAuthorizationUrl(redirectUrl, options) 28 if err != nil { 29 log.Fatal(err) 30 } 31 // Redirect user to this URL to begin SSO authentication 32 fmt.Println(authorizationURL.String()) 33 } ``` * Java AuthorizationUrl.java ```java 1 package com.scalekit; 2 3 import com.scalekit.ScalekitClient; 4 import com.scalekit.internal.http.AuthorizationUrlOptions; 5 6 public class Main { 7 8 public static void main(String[] args) { 9 ScalekitClient scalekitClient = new ScalekitClient( 10 "", // Your Scalekit environment URL 11 "", // Unique identifier for your app 12 "" 13 ); 14 15 AuthorizationUrlOptions options = new AuthorizationUrlOptions(); 16 17 // Send the user to their organization's SSO. To route by connection ID or by 18 // the user's email domain instead, see /sso/guides/authorization-url/ 19 options.setOrganizationId("org_13388706786312310"); 20 21 // redirectUrl: Your callback endpoint that receives the authorization code 22 // Must match the URL registered in your Scalekit dashboard 23 String redirectUrl = "http://localhost:3000/auth/callback"; 24 25 try { 26 String url = scalekitClient 27 .authentication() 28 .getAuthorizationUrl(redirectUrl, options) 29 .toString(); 30 // Redirect user to this URL to begin SSO authentication 31 } catch (Exception e) { 32 System.out.println(e.getMessage()); 33 } 34 } 35 } ``` * Direct URL (No SDK) OAuth2 authorization URL ```sh /oauth/authorize? response_type=code& # OAuth2 authorization code flow client_id=& # Your Scalekit client ID redirect_uri=& # URL-encoded callback URL scope=openid profile email& # Modular SSO returns no refresh token, so leave out offline_access organization_id=org_15421144869927830 # Route to this organization's SSO ``` To route by connection ID or by the user’s email domain instead, see [Authorization URL parameters](/sso/guides/authorization-url/). Example with actual values ```http https://tinotat-dev.scalekit.dev/oauth/authorize? response_type=code& client_id=skc_88036702639096097& redirect_uri=http%3A%2F%2Flocalhost%3A3000%2Fauth%2Fcallback& scope=openid%20profile%20email& organization_id=org_15421144869927830 ``` Scalekit sends the user to their organization’s identity provider. Once they sign in there, Scalekit sends them to your callback URL with a one-time code. 5. ## Read the user’s profile at your callback [Section titled “Read the user’s profile at your callback”](#read-the-users-profile-at-your-callback) Add an endpoint at your callback URL. It receives a `code`, or an `error` and `error_description` if the login failed. Exchange the code for the user’s profile: * Node.js Fetch user profile ```javascript 1 // Extract authentication parameters from the callback request 2 const { code, error, error_description } = req.query; 3 4 if (error) { 5 // The login failed at Scalekit or at the identity provider 6 return res.status(401).send('Sign-in failed'); 7 } 8 9 // The same callback URL you passed to getAuthorizationUrl 10 const redirectUri = 'http://localhost:3000/auth/callback'; 11 const result = await scalekit.authenticateWithCode(code, redirectUri); 12 const userEmail = result.user.email; 13 14 // Create a session for the authenticated user and grant appropriate access permissions ``` * Python Fetch user profile ```py 1 from scalekit import CodeAuthenticationOptions 2 3 # Extract authentication parameters from the callback request 4 code = request.args.get('code') 5 error = request.args.get('error') 6 error_description = request.args.get('error_description') 7 8 if error: 9 raise Exception(error_description) 10 11 # The same callback URL you passed to get_authorization_url 12 redirect_uri = 'http://localhost:3000/auth/callback' 13 result = scalekit_client.authenticate_with_code(code, redirect_uri, CodeAuthenticationOptions()) 14 15 # Access normalized user profile information 16 user_email = result['user']['email'] 17 18 # Create a session for the authenticated user and grant appropriate access permissions ``` * Go Fetch user profile ```go 1 // Extract authentication parameters from the callback request 2 code := r.URL.Query().Get("code") 3 if errCode := r.URL.Query().Get("error"); errCode != "" { 4 // The login failed at Scalekit or at the identity provider 5 log.Printf("SSO login failed: %s: %s", errCode, r.URL.Query().Get("error_description")) 6 http.Error(w, "Sign-in failed", http.StatusUnauthorized) 7 return 8 } 9 10 // The same callback URL you passed to GetAuthorizationUrl 11 redirectUrl := "http://localhost:3000/auth/callback" 12 result, err := scalekitClient.AuthenticateWithCode(r.Context(), code, redirectUrl, scalekit.AuthenticationOptions{}) 13 14 if err != nil { 15 // The code exchange failed 16 http.Error(w, "Sign-in failed", http.StatusUnauthorized) 17 return 18 } 19 20 // Access normalized user profile information 21 log.Printf("Signed in %s", result.User.Email) 22 23 // Create a session for the authenticated user and grant appropriate access permissions ``` * Java Fetch user profile ```java 1 // Extract authentication parameters from the callback request 2 String code = request.getParameter("code"); 3 String error = request.getParameter("error"); 4 String errorDescription = request.getParameter("error_description"); 5 6 if (error != null && !error.isEmpty()) { 7 // The login failed at Scalekit or at the identity provider 8 return; 9 } 10 11 try { 12 // The same callback URL you passed to getAuthorizationUrl 13 String redirectUrl = "http://localhost:3000/auth/callback"; 14 AuthenticationResponse result = scalekitClient 15 .authentication() 16 .authenticateWithCode(code, redirectUrl, new AuthenticationOptions()); 17 String userEmail = result.getIdTokenClaims().getEmail(); 18 19 // Create a session for the authenticated user and grant appropriate access permissions 20 } catch (Exception e) { 21 // Handle token exchange or validation errors 22 } ``` To read the claims in the tokens yourself, validate them with the SDK: * Node.js Validate tokens ```js // Validate and decode the ID token from the authentication result const idTokenClaims = await scalekit.validateToken(result.idToken); // Validate and decode the access token const accessTokenClaims = await scalekit.validateToken(result.accessToken); ``` * Python Validate tokens ```py # Validate and decode the ID token from the authentication result id_token_claims = scalekit_client.validate_token(result["id_token"]) # Validate and decode the access token access_token_claims = scalekit_client.validate_token(result["access_token"]) ``` * Go Validate tokens ```go // Validate and decode the access token (uses JWKS from the client) accessTokenClaims, err := scalekitClient.GetAccessTokenClaims(r.Context(), result.AccessToken) if err != nil { // handle error } ``` * Java Validate tokens ```java // The SDK validates the ID token and returns its claims in the result IdTokenClaims idTokenClaims = result.getIdTokenClaims(); // Validate and decode the access token Map accessTokenClaims = scalekitClient .authentication() .validateAccessTokenAndGetClaims(result.getAccessToken()); ``` - Auth result ```js { user: { email: 'john@example.com', familyName: 'Doe', givenName: 'John', username: 'john@example.com', id: 'conn_70087756662964366;dcc62570-6a5a-4819-b11b-d33d110c7716' }, idToken: 'eyJhbGciOiJSU..bcLQ', accessToken: 'eyJhbGciO..', expiresIn: 899 } ``` - ID token (decoded) ```js 1 { 2 amr: [ 'conn_70087756662964366' ], // SSO connection ID 3 at_hash: 'yMGIBg7BkmIGgD6_dZPEGQ', 4 aud: [ 'skc_70087756327420046' ], 5 azp: 'skc_70087756327420046', 6 c_hash: '4x7qsXnlRw6dRC6twnuENw', 7 client_id: 'skc_70087756327420046', 8 email: 'john@example.com', 9 exp: 1758952038, 10 family_name: 'Doe', 11 given_name: 'John', 12 iat: 1758692838, 13 iss: '', 14 oid: 'org_70087756646187150', 15 preferred_username: 'john@example.com', 16 sid: 'ses_91646612652163629', 17 sub: 'conn_70087756662964366;e964d135-35c7-4a13-a3b4-2579a1cdf4e6' 18 } ``` - Access token (decoded) ```js { "iss": "", "sub": "conn_70087756662964366;dcc62570-6a5a-4819-b11b-d33d110c7716", "aud": [ "skc_70087756327420046" ], "exp": 1758693916, "iat": 1758693016, "nbf": 1758693016, "client_id": "skc_70087756327420046", "jti": "tkn_91646913048216109" } ``` `user.id` is the ID token’s `sub`: the connection ID and the user’s ID at the identity provider, joined by `;`. The ID token’s `oid` claim is the user’s organization ID. See [Normalized user profile](/sso/guides/user-profile-details/) for every field. Before you go to production, check a `state` value on each callback and find or create the user in your database. See [Handle the callback and find the user](/authenticate/sso/handle-callback/). 6. ## Check it worked [Section titled “Check it worked”](#check-it-worked) 1. Open the authorization URL from step 4 with your test organization’s ID. The SSO simulator opens in place of a real identity provider. 2. Leave **User Login via SSO** selected, enter a user name such as `jane` (the domain is `example.com`) and a first and last name, and select **Simulate Login**. Your callback receives a `code`, and the exchange returns a profile with the email and name you entered. If the callback receives an `error` instead, look it up in the [SSO error reference](/sso/reference/sso-integration-errors/). For more test cases, such as IdP-initiated login and error scenarios, see [Test SSO](/sso/guides/test-sso/). ## Next [Section titled “Next”](#next) [How Modular SSO works](/authenticate/sso/how-it-works/)Organizations, connections, domains and what your callback receives. [Handle the callback and find the user](/authenticate/sso/handle-callback/)Check the state, find or create the user and start your session. --- # DOCUMENT BOUNDARY --- # Admin portal > Implement Scalekit's self-serve admin portal to let customers configure SSO and SCIM via a shareable link or embedded iframe The admin portal provides a self-serve interface for customers to configure single sign-on (SSO) and directory sync (SCIM) connections. Scalekit hosts the portal and provides two integration methods: generate a shareable link through the dashboard or programmatically embed the portal in your application using an iframe. For the broader customer onboarding workflow, see [Onboard enterprise customers](/sso/guides/onboard-enterprise-customers/). For self-serve management by signed-in users (members, profiles, domains, SSO, SCIM, session policy), redirect to Hosted UI widgets at `/ui/`. See [Hosted UI widgets](/authenticate/manage-users-orgs/hosted-widgets/) for when to use each option. Use the Admin portal for shareable links or iframe embeds aimed at enterprise IT admins. ## Generate shareable portal link Recommended Generate a shareable link through the Scalekit dashboard to give customers access to the admin portal. This method requires no code and is ideal for quick setup. ### Create the portal link 1. Log in to the [Scalekit dashboard](https://app.scalekit.com) 2. Go to **Organizations** 3. Select the target organization 4. Click **Generate link** to create a shareable admin portal link The generated link follows this format: Portal link example ```http https://your-app.scalekit.dev/magicLink/2cbe56de-eec4-41d2-abed-90a5b82286c4_p ``` ### Link properties | Property | Details | | -------------- | ------------------------------------------------------------------------------- | | **Expiration** | Links expire after 7 days | | **Revocation** | Revoke links anytime from the dashboard | | **Sharing** | Share via email, Slack, or any preferred channel | | **Security** | Anyone with the link can view and update the organization’s connection settings | Security consideration Treat portal links as sensitive credentials. Anyone with the link can view and modify the organization’s SSO and SCIM configuration. ## Embed the admin portal API Embed the admin portal directly in your application using an iframe. This allows customers to configure SSO and SCIM without leaving your app, creating a seamless experience within your settings or admin interface. The portal link must be generated programmatically on each page load for security. Each generated link is single-use and expires after 1 minute, though once loaded, the session remains active for up to 6 hours. * Node.js ```bash npm install @scalekit-sdk/node ``` * Python ```sh pip install scalekit-sdk-python ``` * Go ```sh go get -u github.com/scalekit-inc/scalekit-sdk-go/v2 ``` * Java The Java SDK is published to Scalekit’s Maven repository, `https://us-maven.pkg.dev/scalekit-public/java`. Add it to your build next to Maven Central. It needs no credentials. If your builds download dependencies only through a mirror such as Nexus or Artifactory, add this URL to the mirror instead. For Maven, add the `` and `` entries to the matching sections of your existing `pom.xml`. ```groovy // Gradle: build.gradle repositories { mavenCentral() maven { url "https://us-maven.pkg.dev/scalekit-public/java" } } dependencies { implementation "com.scalekit:scalekit-sdk-java:2.6.1" } ``` ```xml scalekit https://us-maven.pkg.dev/scalekit-public/java com.scalekit scalekit-sdk-java 2.6.1 ``` ### Generate portal link Use the Scalekit SDK to generate a unique, embeddable admin portal link for an organization. Call this API endpoint each time you render the page containing the iframe. * Node.js Express.js ```javascript import { Scalekit } from '@scalekit-sdk/node'; const scalekit = new Scalekit( process.env.SCALEKIT_ENVIRONMENT_URL, process.env.SCALEKIT_CLIENT_ID, process.env.SCALEKIT_CLIENT_SECRET, ); async function generatePortalLink(organizationId) { const link = await scalekit.organization.generatePortalLink(organizationId); return link.location; // Use as iframe src } ``` * Python Flask ```python from scalekit import ScalekitClient import os scalekit_client = ScalekitClient( env_url=os.environ.get("SCALEKIT_ENVIRONMENT_URL"), client_id=os.environ.get("SCALEKIT_CLIENT_ID"), client_secret=os.environ.get("SCALEKIT_CLIENT_SECRET") ) def generate_portal_link(organization_id): link = scalekit_client.organization.generate_portal_link(organization_id) return link.location # Use as iframe src ``` * Go Gin ```go 1 import ( 2 "context" 3 "os" 4 5 scalekit "github.com/scalekit-inc/scalekit-sdk-go/v2" 6 ) 7 8 var scalekitClient = scalekit.NewScalekitClient( 9 os.Getenv("SCALEKIT_ENVIRONMENT_URL"), 10 os.Getenv("SCALEKIT_CLIENT_ID"), 11 os.Getenv("SCALEKIT_CLIENT_SECRET"), 12 ) 13 14 func generatePortalLink(organizationID string) (string, error) { 15 ctx := context.Background() 16 link, err := scalekitClient.Organization().GeneratePortalLink(ctx, organizationID) 17 if err != nil { 18 return "", err 19 } 20 return link.Location, nil // Use as iframe src 21 } ``` * Java Spring Boot ```java 1 import com.scalekit.ScalekitClient; 2 import com.scalekit.grpc.scalekit.v1.organizations.Link; 3 import com.scalekit.grpc.scalekit.v1.organizations.Feature; 4 import java.util.Arrays; 5 6 ScalekitClient scalekitClient = new ScalekitClient( 7 System.getenv("SCALEKIT_ENVIRONMENT_URL"), 8 System.getenv("SCALEKIT_CLIENT_ID"), 9 System.getenv("SCALEKIT_CLIENT_SECRET") 10 ); 11 12 public String generatePortalLink(String organizationId) { 13 Link portalLink = scalekitClient.organizations() 14 .generatePortalLink(organizationId, Arrays.asList(Feature.sso, Feature.dir_sync)); 15 return portalLink.getLocation(); // Use as iframe src 16 } ``` The API returns a JSON object with the portal link. Use the `location` property as the iframe `src`: API response ```json { "id": "8930509d-68cf-4e2c-8c6d-94d2b5e2db43", "location": "https://random-subdomain.scalekit.dev/magicLink/8930509d-68cf-4e2c-8c6d-94d2b5e2db43", "expireTime": "2024-10-03T13:35:50.563013Z" } ``` Embed portal in iframe ```html ``` Embed the portal in your application’s settings or admin section where customers manage authentication configuration. ### Configuration and session | Setting | Requirement | | --------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | **Redirect URI** | Register the domain that hosts the iframe (your application’s own domain) as an **Allowed callback URL** at **Authentication** > **Redirects** > **Allowed Callback URLs** | | **iframe attributes** | Include `allow="clipboard-write"` for copy-paste functionality | | **Dimensions** | Minimum recommended height: 600px | | **Link expiration** | Generated links expire after 1 minute if not loaded | | **Session duration** | Portal session remains active for up to 6 hours once loaded | | **Single-use** | Each generated link can only be used once to initialize a session | Register the embedding domain The embedded portal loads only on domains you have registered. The domain of the page that hosts the iframe must be listed as an allowed callback URL (see the table above). If it is missing, the browser blocks the portal with a Content Security Policy (`frame-ancestors`) error and the iframe stays blank. ## Customize the admin portal Match the admin portal to your brand identity. Configure branding at **Settings** > **Branding**: | Option | Description | | ---------------- | --------------------------------------------------------- | | **Logo** | Upload your company logo (displayed in the portal header) | | **Accent color** | Set the primary color to match your brand palette | | **Favicon** | Provide a custom favicon for browser tabs | For additional customization options including custom domains, see the [Custom domain guide](/guides/custom-domain/). [SSO integrations](/guides/integrations/sso-integrations/)Administrator guides to set up SSO integrations [Portal events](/authenticate/sso/admin-portal-events/)Listen to the browser events emitted from the embedded admin portal --- # DOCUMENT BOUNDARY --- # Choose how to integrate Modular SSO > Pick the Modular SSO guide that matches how your app signs users in today: your own code, Auth0, Amazon Cognito, Firebase, Supabase or Auth.js. How you add Modular SSO depends on what signs users in to your app today. | Your app signs users in with | How Scalekit fits in | Guide | | ------------------------------------------------------------------------------------ | ---------------------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------- | | Your own code: your backend checks passwords or sends codes, and creates the session | Your backend calls the Scalekit SDK to start the login and to read the user from the callback | [Quickstart](/authenticate/sso/add-modular-sso/), then [Handle the callback and find the user](/authenticate/sso/handle-callback/) | | Auth0 | You add Scalekit to Auth0 as an OpenID Connect (OIDC) provider. Auth0 keeps the session | [Auth0](/guides/integrations/auth-systems/auth0/) | | Amazon Cognito | You add Scalekit to your Cognito user pool as an OIDC identity provider. Cognito keeps the session | [AWS Cognito](/guides/integrations/auth-systems/aws-cognito/) | | Firebase Authentication | You add Scalekit as an OIDC provider in Firebase, or sign the user in to Firebase from your backend after the Scalekit login | [Firebase](/guides/integrations/auth-systems/firebase/) | | Supabase Auth | You add Scalekit to Supabase as a custom OIDC provider. Supabase keeps the session | [Supabase](/guides/integrations/auth-systems/supabase/) | | Auth.js in a Next.js app | You add Scalekit to Auth.js as an OIDC provider | [Add enterprise SSO to Next.js with Auth.js](/cookbooks/add-enterprise-sso-nextjs-authjs/) | With an auth system, that system talks to Scalekit and creates the session, so your app writes little or no Scalekit code. You still set up Scalekit the same way: put the environment in **Modular Auth** mode, create an organization for each customer, and have their IT admin connect their identity provider (IdP). Your auth system isn’t listed? If it can add an OIDC provider, add Scalekit as one, using your environment URL as the issuer and your client ID and secret. Otherwise, use the SDK from your backend as the quickstart shows. ## Next [Section titled “Next”](#next) Whichever way you integrate, each customer needs an organization and a working connection. See [Onboard an enterprise customer](/sso/guides/onboard-enterprise-customers/). --- # DOCUMENT BOUNDARY --- # Enterprise SSO code samples > Code samples demonstrating Single Sign-On implementations with Express.js, PHP Symfony, .NET Core, Firebase, AWS Cognito, and Next.js ### [Add SSO to Express.js apps](https://github.com/scalekit-inc/nodejs-example-apps/tree/main/sso-express-example) [Implement Scalekit SSO in a Node.js Express application. Includes middleware setup for secure session handling](https://github.com/scalekit-inc/nodejs-example-apps/tree/main/sso-express-example) ### [Add SSO to PHP Symfony apps](https://github.com/scalekit-developers/scalekit-php-symfony-sso) [Call Scalekit OIDC endpoints from Symfony with no PHP SDK. Try handshake-only login or Modular SSO with a local user store](https://github.com/scalekit-developers/scalekit-php-symfony-sso) ### [Add SSO to .NET Core apps](https://github.com/scalekit-inc/dotnet-example-apps) [Secure .NET Core applications with Scalekit SSO. Demonstrates authentication pipelines and user claims management](https://github.com/scalekit-inc/dotnet-example-apps) ### [Add SSO to Spring Boot apps](https://github.com/scalekit-developers/scalekit-springboot-example) [Integrate Scalekit SSO with Spring Security. Shows how to configure security filters and protect Java endpoints](https://github.com/scalekit-developers/scalekit-springboot-example) ### [Add SSO to Python FastAPI](https://github.com/scalekit-developers/scalekit-fastapi-example) [Add enterprise SSO to FastAPI services using Scalekit. Includes async route protection and user session validation](https://github.com/scalekit-developers/scalekit-fastapi-example) ### [Add SSO to Go applications](https://github.com/scalekit-developers/scalekit-go-example) [Implement Scalekit SSO in Go. Features idiomatically written middleware for securing HTTP handlers](https://github.com/scalekit-developers/scalekit-go-example) ### [Add SSO to Next.js apps](https://github.com/scalekit-developers/scalekit-nextjs-demo) [Secure Next.js applications with Scalekit. Covers both App Router and Pages Router authentication patterns](https://github.com/scalekit-developers/scalekit-nextjs-demo) ### Scalekit SSO + Your own auth system ### [Connect Firebase Auth with SSO](https://github.com/scalekit-inc/scalekit-firebase-sso) [Enable Enterprise SSO for Firebase apps using Scalekit. Learn to link Scalekit identities with Firebase Authentication](https://github.com/scalekit-inc/scalekit-firebase-sso) ### [Connect AWS Cognito with SSO](https://github.com/scalekit-inc/scalekit-cognito-sso) [Add Enterprise SSO to Cognito user pools via Scalekit. Step-by-step guide to federating identity providers](https://github.com/scalekit-inc/scalekit-cognito-sso) ### [Cognito + Scalekit for Next.js](https://github.com/scalekit-inc/nextjs-example-apps/tree/main/cognito-scalekit) [Integrate Cognito and Scalekit SSO in Next.js. Uses OIDC protocols to secure your full-stack React application](https://github.com/scalekit-inc/nextjs-example-apps/tree/main/cognito-scalekit) ## Admin portal ### [Embed admin portal](https://github.com/scalekit-inc/nodejs-example-apps/tree/main/embed-admin-portal-sample) [Embed the Scalekit Admin Portal into your app via **iframe**. Node.js example for generating secure admin sessions](https://github.com/scalekit-inc/nodejs-example-apps/tree/main/embed-admin-portal-sample) --- # DOCUMENT BOUNDARY --- # Handle the callback and find the user > Build the Modular SSO callback: check the state and errors, exchange the code, find or create the user in your database and start your app's session. At the end of an SSO login, Scalekit redirects the user to your callback URL. This page builds that endpoint for production. By the end, your app: * starts each login with a `state` value and rejects responses it didn’t ask for * turns failed logins into a clear message * finds or creates the user in your database, keyed on a stable ID rather than an email address * starts your own session ## Before you start [Section titled “Before you start”](#before-you-start) * Complete the [quickstart](/authenticate/sso/add-modular-sso/): your environment is in **Modular Auth** mode, and your callback URL is registered under **Authentication** > **Redirect URLs** > **Allowed callback URLs**. * Add these to your `.env` file. `REDIRECT_URI` is your registered callback URL. `SESSION_SECRET` signs your app’s session cookie; use a long random value. .env ```sh SCALEKIT_ENVIRONMENT_URL= SCALEKIT_CLIENT_ID= SCALEKIT_CLIENT_SECRET= REDIRECT_URI=http://localhost:3000/auth/callback SESSION_SECRET= ``` ## Build the endpoints [Section titled “Build the endpoints”](#build-the-endpoints) 1. ## Install the SDK and a web framework [Section titled “Install the SDK and a web framework”](#install-the-sdk-and-a-web-framework) * Node.js ```sh npm install @scalekit-sdk/node express express-session dotenv ``` * Python ```sh pip install scalekit-sdk-python flask python-dotenv ``` * Go ```sh go get -u github.com/scalekit-inc/scalekit-sdk-go/v2 ``` * Java Add `com.scalekit:scalekit-sdk-java` to a Spring Boot web app. See [Install the SDK](/authenticate/sso/add-modular-sso/#set-up-scalekit) for the Maven and Gradle lines. 2. ## Add the login and callback endpoints [Section titled “Add the login and callback endpoints”](#add-the-login-and-callback-endpoints) The example has two endpoints: * **`/auth/sso`** starts a login. It creates a random `state` value, stores it in the user’s browser session and passes it in the authorization URL. It takes the customer’s organization ID; in your app, look it up from your records, for example by the email domain the user entered. * **`/auth/callback`** finishes it. It checks the response, exchanges the code for the user’s profile, finds or creates the user and starts your session. - Node.js server.mjs ```javascript 1 import crypto from 'node:crypto'; 2 import 'dotenv/config'; 3 import express from 'express'; 4 import session from 'express-session'; 5 import { ScalekitClient } from '@scalekit-sdk/node'; 6 7 const scalekit = new ScalekitClient( 8 process.env.SCALEKIT_ENVIRONMENT_URL, 9 process.env.SCALEKIT_CLIENT_ID, 10 process.env.SCALEKIT_CLIENT_SECRET, 11 ); 12 const redirectUri = process.env.REDIRECT_URI; 13 14 const app = express(); 15 app.use( 16 session({ secret: process.env.SESSION_SECRET, resave: false, saveUninitialized: false }), 17 ); 18 19 // Your users table. Replace with your database. 20 const users = new Map(); 21 22 function findOrCreateUser({ organizationId, idpUserId, email, name }) { 23 const key = `${organizationId}:${idpUserId}`; 24 let user = users.get(key); 25 if (!user) { 26 user = { id: crypto.randomUUID(), organizationId, idpUserId }; 27 users.set(key, user); 28 } 29 // Keep the profile current: email and name can change at the IdP 30 Object.assign(user, { email, name }); 31 return user; 32 } 33 34 // Start an SSO login for one of your customers 35 app.get('/auth/sso', (req, res) => { 36 const state = crypto.randomBytes(16).toString('hex'); 37 req.session.ssoState = state; 38 const url = scalekit.getAuthorizationUrl(redirectUri, { 39 organizationId: req.query.organization_id, 40 state, 41 }); 42 res.redirect(url); 43 }); 44 45 app.get('/auth/callback', async (req, res, next) => { 46 const { code, state, error, error_description } = req.query; 47 const expectedState = req.session.ssoState; 48 delete req.session.ssoState; 49 50 if (error) { 51 console.warn(`SSO login failed: ${error}: ${error_description}`); 52 return res.status(401).send('Sign-in failed'); 53 } 54 if (!state || state !== expectedState) { 55 return res.status(400).send('Sign-in failed: unexpected state'); 56 } 57 58 let result, claims; 59 try { 60 result = await scalekit.authenticateWithCode(code, redirectUri); 61 // The ID token's oid claim is the user's organization 62 claims = await scalekit.validateToken(result.idToken); 63 } catch (err) { 64 console.warn('Code exchange failed:', err.message); 65 return res.status(401).send('Sign-in failed'); 66 } 67 68 const profile = result.user; 69 const user = findOrCreateUser({ 70 organizationId: claims.oid, 71 idpUserId: profile.id.slice(profile.id.indexOf(';') + 1), 72 email: profile.email, 73 name: [profile.givenName, profile.familyName].filter(Boolean).join(' '), 74 }); 75 76 // Start a fresh session for the user, so a session ID set before login can't be reused 77 req.session.regenerate((err) => { 78 if (err) return next(err); 79 req.session.userId = user.id; 80 res.redirect('/'); 81 }); 82 }); 83 84 app.listen(3000, () => console.log('Listening on http://localhost:3000')); ``` Run it with `node server.mjs`. - Python app.py ```python 1 import os 2 import secrets 3 4 from dotenv import load_dotenv 5 from flask import Flask, redirect, request, session 6 from scalekit import AuthorizationUrlOptions, CodeAuthenticationOptions, ScalekitClient 7 8 load_dotenv() 9 10 scalekit_client = ScalekitClient( 11 env_url=os.environ["SCALEKIT_ENVIRONMENT_URL"], 12 client_id=os.environ["SCALEKIT_CLIENT_ID"], 13 client_secret=os.environ["SCALEKIT_CLIENT_SECRET"], 14 ) 15 redirect_uri = os.environ["REDIRECT_URI"] 16 17 app = Flask(__name__) 18 app.secret_key = os.environ["SESSION_SECRET"] 19 20 # Your users table. Replace with your database. 21 users = {} 22 23 24 def find_or_create_user(organization_id, idp_user_id, email, name): 25 key = (organization_id, idp_user_id) 26 user = users.get(key) 27 if user is None: 28 user = {"id": secrets.token_hex(16), "organization_id": organization_id, "idp_user_id": idp_user_id} 29 users[key] = user 30 # Keep the profile current: email and name can change at the IdP 31 user.update(email=email, name=name) 32 return user 33 34 35 # Start an SSO login for one of your customers 36 @app.route("/auth/sso") 37 def start_sso(): 38 state = secrets.token_urlsafe(16) 39 session["sso_state"] = state 40 options = AuthorizationUrlOptions() 41 options.organization_id = request.args.get("organization_id") 42 options.state = state 43 return redirect(scalekit_client.get_authorization_url(redirect_uri=redirect_uri, options=options)) 44 45 46 @app.route("/auth/callback") 47 def callback(): 48 expected_state = session.pop("sso_state", None) 49 error = request.args.get("error") 50 if error: 51 app.logger.warning("SSO login failed: %s: %s", error, request.args.get("error_description")) 52 return "Sign-in failed", 401 53 state = request.args.get("state") 54 if not state or state != expected_state: 55 return "Sign-in failed: unexpected state", 400 56 57 try: 58 result = scalekit_client.authenticate_with_code( 59 request.args.get("code"), redirect_uri, CodeAuthenticationOptions() 60 ) 61 except Exception as e: 62 app.logger.warning("Code exchange failed: %s", e) 63 return "Sign-in failed", 401 64 65 profile = result["user"] 66 user = find_or_create_user( 67 # From the ID token's oid claim: the user's organization 68 organization_id=result["organization_id"], 69 idp_user_id=profile["id"].split(";", 1)[1], 70 email=profile.get("email"), 71 name=" ".join(filter(None, [profile.get("givenName"), profile.get("familyName")])), 72 ) 73 74 # Start a fresh session for the user 75 session.clear() 76 session["user_id"] = user["id"] 77 return redirect("/") 78 79 80 if __name__ == "__main__": 81 app.run(port=3000) ``` Run it with `python app.py`. - Go main.go ```go 1 package main 2 3 import ( 4 "crypto/rand" 5 "encoding/hex" 6 "log" 7 "net/http" 8 "os" 9 "strings" 10 "sync" 11 12 scalekit "github.com/scalekit-inc/scalekit-sdk-go/v2" 13 ) 14 15 var ( 16 scalekitClient = scalekit.NewScalekitClient( 17 os.Getenv("SCALEKIT_ENVIRONMENT_URL"), 18 os.Getenv("SCALEKIT_CLIENT_ID"), 19 os.Getenv("SCALEKIT_CLIENT_SECRET"), 20 ) 21 redirectURI = os.Getenv("REDIRECT_URI") 22 23 // Your users table. Replace with your database. 24 usersMu sync.Mutex 25 users = map[string]*AppUser{} 26 ) 27 28 type AppUser struct { 29 ID, OrganizationID, IdpUserID, Email, Name string 30 } 31 32 func findOrCreateUser(organizationID, idpUserID, email, name string) *AppUser { 33 usersMu.Lock() 34 defer usersMu.Unlock() 35 key := organizationID + ":" + idpUserID 36 user, ok := users[key] 37 if !ok { 38 user = &AppUser{ID: randomHex(), OrganizationID: organizationID, IdpUserID: idpUserID} 39 users[key] = user 40 } 41 // Keep the profile current: email and name can change at the IdP 42 user.Email, user.Name = email, name 43 return user 44 } 45 46 func randomHex() string { 47 b := make([]byte, 16) 48 if _, err := rand.Read(b); err != nil { 49 panic(err) 50 } 51 return hex.EncodeToString(b) 52 } 53 54 // Start an SSO login for one of your customers 55 func startSSO(w http.ResponseWriter, r *http.Request) { 56 state := randomHex() 57 http.SetCookie(w, &http.Cookie{ 58 Name: "sso_state", Value: state, Path: "/auth", MaxAge: 600, 59 HttpOnly: true, Secure: true, SameSite: http.SameSiteLaxMode, 60 }) 61 authURL, err := scalekitClient.GetAuthorizationUrl(redirectURI, scalekit.AuthorizationUrlOptions{ 62 OrganizationId: r.URL.Query().Get("organization_id"), 63 State: state, 64 }) 65 if err != nil { 66 http.Error(w, "Could not start sign-in", http.StatusInternalServerError) 67 return 68 } 69 http.Redirect(w, r, authURL.String(), http.StatusFound) 70 } 71 72 func callback(w http.ResponseWriter, r *http.Request) { 73 q := r.URL.Query() 74 stateCookie, cookieErr := r.Cookie("sso_state") 75 http.SetCookie(w, &http.Cookie{Name: "sso_state", Path: "/auth", MaxAge: -1}) 76 77 if errCode := q.Get("error"); errCode != "" { 78 log.Printf("SSO login failed: %s: %s", errCode, q.Get("error_description")) 79 http.Error(w, "Sign-in failed", http.StatusUnauthorized) 80 return 81 } 82 if cookieErr != nil || q.Get("state") == "" || q.Get("state") != stateCookie.Value { 83 http.Error(w, "Sign-in failed: unexpected state", http.StatusBadRequest) 84 return 85 } 86 87 result, err := scalekitClient.AuthenticateWithCode( 88 r.Context(), q.Get("code"), redirectURI, scalekit.AuthenticationOptions{}, 89 ) 90 if err != nil { 91 log.Printf("Code exchange failed: %v", err) 92 http.Error(w, "Sign-in failed", http.StatusUnauthorized) 93 return 94 } 95 // The ID token's oid claim is the user's organization 96 claims, err := scalekitClient.ValidateToken(r.Context(), result.IdToken) 97 organizationID, _ := claims["oid"].(string) 98 if err != nil || organizationID == "" { 99 log.Printf("ID token check failed: %v", err) 100 http.Error(w, "Sign-in failed", http.StatusUnauthorized) 101 return 102 } 103 104 profile := result.User 105 _, idpUserID, _ := strings.Cut(profile.Id, ";") 106 name := strings.TrimSpace(profile.GivenName + " " + profile.FamilyName) 107 user := findOrCreateUser(organizationID, idpUserID, profile.Email, name) 108 109 // Start your app's session for user.ID here, the way your app does after any login 110 log.Printf("Signed in user %s", user.ID) 111 http.Redirect(w, r, "/", http.StatusFound) 112 } 113 114 func main() { 115 http.HandleFunc("/auth/sso", startSSO) 116 http.HandleFunc("/auth/callback", callback) 117 log.Fatal(http.ListenAndServe(":3000", nil)) 118 } ``` Go doesn’t load `.env` files on its own: export the variables in your shell, then run `go run main.go`. - Java SsoController.java ```java 1 package com.example.sso; 2 3 import com.scalekit.ScalekitClient; 4 import com.scalekit.internal.http.AuthenticationOptions; 5 import com.scalekit.internal.http.AuthenticationResponse; 6 import com.scalekit.internal.http.AuthorizationUrlOptions; 7 import com.scalekit.internal.http.IdTokenClaims; 8 import jakarta.servlet.http.HttpServletRequest; 9 import jakarta.servlet.http.HttpSession; 10 import java.security.SecureRandom; 11 import java.util.HexFormat; 12 import java.util.Map; 13 import java.util.UUID; 14 import java.util.concurrent.ConcurrentHashMap; 15 import org.slf4j.Logger; 16 import org.slf4j.LoggerFactory; 17 import org.springframework.http.ResponseEntity; 18 import org.springframework.web.bind.annotation.GetMapping; 19 import org.springframework.web.bind.annotation.RequestParam; 20 import org.springframework.web.bind.annotation.RestController; 21 22 @RestController 23 public class SsoController { 24 25 private static final Logger log = LoggerFactory.getLogger(SsoController.class); 26 27 private final ScalekitClient scalekitClient = new ScalekitClient( 28 System.getenv("SCALEKIT_ENVIRONMENT_URL"), 29 System.getenv("SCALEKIT_CLIENT_ID"), 30 System.getenv("SCALEKIT_CLIENT_SECRET") 31 ); 32 private final String redirectUri = System.getenv("REDIRECT_URI"); 33 private final SecureRandom random = new SecureRandom(); 34 35 // Your users table. Replace with your database. 36 public record AppUser(String id, String organizationId, String idpUserId, String email, String name) {} 37 private final Map users = new ConcurrentHashMap<>(); 38 39 private AppUser findOrCreateUser(String organizationId, String idpUserId, String email, String name) { 40 // Keep the profile current: email and name can change at the IdP 41 return users.compute(organizationId + ":" + idpUserId, (key, existing) -> new AppUser( 42 existing != null ? existing.id() : UUID.randomUUID().toString(), 43 organizationId, idpUserId, email, name)); 44 } 45 46 // Start an SSO login for one of your customers 47 @GetMapping("/auth/sso") 48 public ResponseEntity startSso( 49 @RequestParam("organization_id") String organizationId, HttpSession session) { 50 byte[] bytes = new byte[16]; 51 random.nextBytes(bytes); 52 String state = HexFormat.of().formatHex(bytes); 53 session.setAttribute("ssoState", state); 54 55 AuthorizationUrlOptions options = new AuthorizationUrlOptions(); 56 options.setOrganizationId(organizationId); 57 options.setState(state); 58 String url = scalekitClient.authentication() 59 .getAuthorizationUrl(redirectUri, options) 60 .toString(); 61 return ResponseEntity.status(302).header("Location", url).build(); 62 } 63 64 @GetMapping("/auth/callback") 65 public ResponseEntity callback( 66 @RequestParam Map params, HttpServletRequest request) { 67 HttpSession session = request.getSession(); 68 String expectedState = (String) session.getAttribute("ssoState"); 69 session.removeAttribute("ssoState"); 70 71 String error = params.get("error"); 72 if (error != null) { 73 log.warn("SSO login failed: {}: {}", error, params.get("error_description")); 74 return ResponseEntity.status(401).body("Sign-in failed"); 75 } 76 String state = params.get("state"); 77 if (state == null || !state.equals(expectedState)) { 78 return ResponseEntity.status(400).body("Sign-in failed: unexpected state"); 79 } 80 81 AuthenticationResponse result; 82 Map claims; 83 try { 84 result = scalekitClient.authentication() 85 .authenticateWithCode(params.get("code"), redirectUri, new AuthenticationOptions()); 86 // Validates the ID token's signature; its oid claim is the user's organization 87 claims = scalekitClient.authentication() 88 .validateAccessTokenAndGetClaims(result.getIdToken()); 89 } catch (Exception e) { 90 log.warn("Code exchange failed: {}", e.getMessage()); 91 return ResponseEntity.status(401).body("Sign-in failed"); 92 } 93 94 IdTokenClaims profile = result.getIdTokenClaims(); 95 String sub = profile.getId(); 96 String name = String.join(" ", 97 java.util.stream.Stream.of(profile.getGivenName(), profile.getFamilyName()) 98 .filter(n -> n != null && !n.isBlank()) 99 .toList()); 100 AppUser user = findOrCreateUser( 101 (String) claims.get("oid"), 102 sub.substring(sub.indexOf(';') + 1), 103 profile.getEmail(), 104 name); 105 106 // Start a fresh session for the user, so a session ID set before login can't be reused 107 session.invalidate(); 108 request.getSession(true).setAttribute("userId", user.id()); 109 return ResponseEntity.status(302).header("Location", "/").build(); 110 } 111 } ``` 3. ## Check the response before you trust it [Section titled “Check the response before you trust it”](#check-the-response-before-you-trust-it) The callback handles three outcomes, in this order: * **An `error` parameter.** The login failed at Scalekit or at the identity provider (IdP). Log `error` and `error_description`, and show the user a short message rather than the raw text. For the common errors and how to fix them, see [Troubleshoot Modular SSO](/authenticate/sso/troubleshooting/), and the [SSO error reference](/sso/reference/sso-integration-errors/) for other codes. * **A `state` that doesn’t match.** The response isn’t for a login this browser started, for example a forged link. Reject it. The stored value is removed on each callback, so the same response can’t be used twice. * **A `code`.** Exchange it once, with the same redirect URI you passed to the authorization URL. The SDK checks the ID token’s signature and returns the user’s profile. 4. ## Find or create the user [Section titled “Find or create the user”](#find-or-create-the-user) Key each user on two values, not on their email: * **The organization ID**, which says which customer the user belongs to. * **The user’s ID at the IdP**: the part of the profile’s `id` (the ID token’s `sub`) after the `;`. The part before it is the connection ID, which changes if your customer deletes their SSO connection and creates a new one. Email addresses change when a user is renamed, and two customers’ IdPs can each assert any address, so an email alone can’t safely identify a user. Store the email and name, and update them at each login. Some IdPs send a changeable value, such as an email address, as the user’s ID; see [Choose a stable user identifier](/sso/guides/user-profile-details/#choose-a-stable-user-identifier), which covers Microsoft Entra ID. If your app already has users who signed in another way, link an SSO user to an existing account only after a check you trust, such as the email domain being one of the organization’s verified domains. 5. ## Start your session [Section titled “Start your session”](#start-your-session) Scalekit doesn’t return a refresh token: after the callback, your app runs the session for as long as your app decides. Start it the way your app does after any login. When the session ends, send the user through SSO again; if they’re still signed in at their IdP, they come straight back. To log a user out, end your app’s session. 6. ## Check it worked [Section titled “Check it worked”](#check-it-worked) 1. Start your app. 2. Find your test organization’s ID under **Organizations** in the dashboard of your development environment. 3. Open `http://localhost:3000/auth/sso?organization_id=`. The SSO simulator opens. 4. Leave **User Login via SSO** selected, enter a user name such as `jane` (the domain is `example.com`) and a first and last name, and select **Simulate Login**. The callback redirects you to `/`, which this example doesn’t serve, so a “not found” page is expected. Your users table has a user with the test organization’s ID, `jane@example.com` and the name you entered. Open `http://localhost:3000/auth/callback?code=x&state=forged`: the response is `400 Sign-in failed: unexpected state`. ## Next [Section titled “Next”](#next) * [Onboard an enterprise customer](/sso/guides/onboard-enterprise-customers/): create their organization and give their IT admin the admin portal. * [Map IdP groups to roles](/sso/guides/sso-user-attributes/): send roles or groups from the IdP and use them in your app. --- # DOCUMENT BOUNDARY --- # How Modular SSO works > The parts of a Modular SSO login: environments, organizations, connections, domains, redirect URLs, and the profile and tokens your callback receives. This page explains the parts of a Modular SSO login and how they fit together. Read it after the [quickstart](/authenticate/sso/add-modular-sso/), or before it if you want the whole picture first. ## Environment [Section titled “Environment”](#environment) An environment holds everything for one stage of your app, such as development or production: its own API credentials, environment URL, organizations and connections. Its credentials are under **Developers** > **Settings** > **API Credentials** in the dashboard. To use Modular SSO, set the environment’s authentication mode to **Modular Auth** in **Settings** > **Authentication Mode**. In this mode your app keeps its users and sessions, and Scalekit returns the verified user to your app. A development environment comes with a test organization and an SSO simulator, so you can test before you have a customer. See [Test SSO](/sso/guides/test-sso/). ## Organization [Section titled “Organization”](#organization) An organization is one of your customers, usually a company, such as Megacorp. Create one for each customer that wants SSO, in the dashboard or with the API. Its ID starts with `org_`. Store the organization ID with the customer’s record in your app. You use it to start their users’ logins, and the ID token at the end of each login tells you which organization the user belongs to. ## Connection [Section titled “Connection”](#connection) A connection links an organization to its identity provider (IdP), such as Okta or Microsoft Entra ID, over SAML or OIDC. Its ID starts with `conn_`. Usually your customer’s IT admin sets up the connection in the [admin portal](/authenticate/sso/admin-portal/): they enter the IdP’s details and test the login. You can also set it up for them from the organization’s page in the dashboard. Each IdP’s setup steps are in the [IdP guides](/guides/integrations/sso-integrations/). ## Domain [Section titled “Domain”](#domain) An organization’s domains are the email domains its users sign in with, such as `megacorp.com`. With a domain on the organization, your app can send a user to the right IdP from their email address alone, without asking which company they’re from. See [Route users to SSO by email domain](/guides/user-auth/check-sso-domain/). ## Redirect URLs [Section titled “Redirect URLs”](#redirect-urls) Scalekit only sends users to URLs you’ve registered under **Authentication** > **Redirect URLs**: * **Allowed callback URL**: where Scalekit sends the user at the end of a login, with a one-time code. Your app exchanges the code for the user’s profile. * **Initiate login URL**: where Scalekit sends a user who started from their IdP’s dashboard, so your app can start the login itself. See [Register redirect URLs](/authenticate/sso/redirect-urls/). ## Start a login: the authorization URL [Section titled “Start a login: the authorization URL”](#start-a-login-the-authorization-url) Your app starts a login by redirecting the user to an authorization URL that the SDK builds. The URL names your callback URL and the customer, by one of: * the connection ID * the organization ID * a domain hint, such as `megacorp.com` * a login hint, the user’s email address, whose domain picks the organization If you pass more than one, Scalekit uses them in a fixed order. See [Authorization URL parameters](/sso/guides/authorization-url/#parameter-precedence). Pass a `state` value too. Scalekit returns it unchanged to your callback, so your app can check that the response belongs to a login it started. ## IdP-initiated login [Section titled “IdP-initiated login”](#idp-initiated-login) Some users start from their IdP’s dashboard, such as an app tile in Okta. Scalekit sends them to your initiate login URL with an `idp_initiated_login` token. Your endpoint reads the organization and connection from the token and starts a normal login with an authorization URL. See [IdP-initiated SSO](/sso/guides/idp-init-sso/). ## What your callback receives [Section titled “What your callback receives”](#what-your-callback-receives) At the end of a login, Scalekit redirects the user to your callback URL with a `code` and the `state` you sent, or with `error` and `error_description` if the login failed. Your app exchanges the code with the SDK and gets: * **The user’s profile**: email, name and the other fields of the [normalized user profile](/sso/guides/user-profile-details/), in the same format for every IdP. * **An ID token**: a signed JWT with the same profile. Its `sub` claim is the connection ID and the user’s ID at the IdP, joined by `;`. Its `oid` claim is the organization ID. * **An access token**. There’s no refresh token: after the login, your app runs the session. To find or create the user in your database, see [Handle the callback and find the user](/authenticate/sso/handle-callback/). ## Admin portal [Section titled “Admin portal”](#admin-portal) The admin portal is a page Scalekit hosts where your customer’s IT admin sets up and tests their SSO connection. Share a link to it, or embed it in your app’s settings page. See [Admin portal](/authenticate/sso/admin-portal/). ## Events [Section titled “Events”](#events) Scalekit sends webhook events when a customer’s SSO connection is created, enabled, disabled or deleted, so your app can turn SSO on for the customer at the right time. See [SSO events](/sso/reference/sso-events/). ## Next [Section titled “Next”](#next) [Choose how to integrate](/authenticate/sso/choose-integration/)Your own code, or an auth system such as Auth0, Cognito, Firebase or Supabase. [Handle the callback and find the user](/authenticate/sso/handle-callback/)Check the response, find or create the user and start your session. --- # DOCUMENT BOUNDARY --- # Troubleshoot Modular SSO > Fix common Modular SSO errors by their exact text: a missing connection selector, unregistered callback URLs, failed code exchanges, IdP-initiated login and SAML problems. This page lists the problems developers hit most often while adding Modular SSO. Find the error you got in the table, then follow its link for the cause and the fix. **You** fix most of them in your app or your Scalekit settings; the ones marked **IT admin** are fixed by your customer’s IT admin in their identity provider (IdP). | Error | When it happens | Who fixes it | | ----------------------------------------------------------------------------------------------------------- | ------------------------ | ------------ | | [`invalid_connection_selector`](#invalid_connection_selector) | Starting the login | You | | [redirect_uri is missing in the client configuration](#redirect_uri-is-missing-in-the-client-configuration) | Starting the login | You | | [unable to retrieve client by id](#unable-to-retrieve-client-by-id) | Starting the login | You | | [`invalid_request`: scope missing](#invalid_request) | Starting the login | You | | [`invalid_scope`](#invalid_scope) | Exchanging the code | You | | [`invalid_grant`: redirect_uri does not correspond](#invalid_grant-redirect_uri-does-not-correspond) | Exchanging the code | You | | [`invalid_grant`: invalid code](#invalid_grant-invalid-code) | Exchanging the code | You | | [`invalid_client`](#invalid_client) | Exchanging the code | You | | [`invalid_idp_initiated_sso`](#invalid_idp_initiated_sso) | Login started at the IdP | You | | [`invalid_in_response_to`](#invalid_in_response_to) | At the IdP (SAML) | You | | [`invalid_saml_metadata`](#invalid_saml_metadata) | At the IdP (SAML) | IT admin | | [`mandatory_attribute_missing`](#mandatory_attribute_missing) | At the IdP | IT admin | | [The user’s name is empty](#the-users-name-is-empty) | After the login | IT admin | | [The admin portal loads a blank page](#the-admin-portal-loads-a-blank-page) | Admin portal | IT admin | For other codes, see the [SSO error reference](/sso/reference/sso-integration-errors/). To see what happened in one login, find it under **Logs** in the dashboard; see [Auth logs](/authenticate/sso/logs/). ## Where errors show up [Section titled “Where errors show up”](#where-errors-show-up) * **On your callback URL.** When a login fails at Scalekit or at the IdP, Scalekit redirects the user to your callback URL with `error`, `error_description` and your `state`, instead of a `code`. * **From the code exchange.** The SDK throws an error that carries Scalekit’s JSON response, such as `{"error":"invalid_grant","error_description":"invalid code"}`. In Node.js, read it from `err.response.data`; in Python, it’s in the exception’s message. Go by the `error` value, not the HTTP status. * **On a Scalekit error page.** When Scalekit can’t trust the callback URL or the client ID, it can’t redirect the user, so it shows the error itself. ## Starting the login [Section titled “Starting the login”](#starting-the-login) ### `invalid_connection_selector` [Section titled “invalid_connection_selector”](#invalid_connection_selector) You fix ```text error=invalid_connection_selector error_description=Need additional details to initiate SSO. Atleast one of: (organization_id, external_id, connection_id, domain). ``` **Cause:** Scalekit couldn’t tell which customer’s IdP to send the user to. The authorization URL has no organization ID, connection ID, domain or login hint, or the one it has isn’t in this environment, such as an organization ID copied from development into production, or an email domain that isn’t on any organization. **Fix:** Pass one of them when you build the [authorization URL](/sso/guides/authorization-url/), using IDs from the same environment as your API credentials. To route by email, first add the customer’s domain to their organization; see [Route users to SSO by email domain](/guides/user-auth/check-sso-domain/). ### redirect_uri is missing in the client configuration [Section titled “redirect_uri is missing in the client configuration”](#redirect_uri-is-missing-in-the-client-configuration) You fix Scalekit shows this on its own error page, with HTTP status 400: ```text The requested redirect_uri is missing in the client configuration. If you have any questions, you may contact the administrator of the application. ``` **Cause:** The callback URL in your authorization URL isn’t one of the environment’s allowed callback URLs. The match is exact, so `http://localhost:3000/auth/callback` and `http://localhost:3001/auth/callback` are different URLs. **Fix:** Add the URL under **Authentication** > **Redirect URLs** > **Allowed callback URLs**; see [Register redirect URLs](/authenticate/sso/redirect-urls/). An app served from several hosts, such as one per region or per customer subdomain, needs each callback URL registered. ### unable to retrieve client by id [Section titled “unable to retrieve client by id”](#unable-to-retrieve-client-by-id) You fix **Cause:** Scalekit shows this on its own error page, with HTTP status 400, when the client ID in the authorization URL doesn’t belong to this environment. **Fix:** Take `SCALEKIT_ENVIRONMENT_URL` and `SCALEKIT_CLIENT_ID` from the same environment, under **Developers** > **Settings** > **API Credentials**. ### `invalid_request` [Section titled “invalid_request”](#invalid_request) You fix ```text error=invalid_request error_description=The scope of your request is missing. Please ensure some scopes are requested. If you have any questions, you may contact the administrator of the application. ``` **Cause:** The authorization URL has no `scope`. The SDK adds `openid profile email` for you, so this happens when the URL is built by hand. **Fix:** Build the URL with the SDK, or add `scope=openid profile email`. ## Exchanging the code [Section titled “Exchanging the code”](#exchanging-the-code) ### `invalid_scope` [Section titled “invalid_scope”](#invalid_scope) You fix ```json {"error":"invalid_scope","error_description":"invalid scope offline_access not allowed"} ``` **Cause:** The authorization URL asked for `offline_access`, which requests a refresh token. The login succeeds and the code exchange fails. In Modular SSO your app runs the session, so Scalekit doesn’t issue refresh tokens. **Fix:** Remove `offline_access` from the scopes. When your app’s session ends, send the user through SSO again; see [Start your session](/authenticate/sso/handle-callback/#start-your-session). ### `invalid_grant`: redirect_uri does not correspond [Section titled “invalid_grant: redirect_uri does not correspond”](#invalid_grant-redirect_uri-does-not-correspond) You fix ```json {"error":"invalid_grant","error_description":"redirect_uri does not correspond"} ``` **Cause:** The redirect URI you passed to the code exchange isn’t the one you passed to the authorization URL. **Fix:** Pass the same URL to both. Keep it in one setting, such as the `REDIRECT_URI` environment variable the [callback guide](/authenticate/sso/handle-callback/) uses, rather than building it from the incoming request, which can differ behind a proxy. ### `invalid_grant`: invalid code [Section titled “invalid_grant: invalid code”](#invalid_grant-invalid-code) You fix ```json {"error":"invalid_grant","error_description":"invalid code"} ``` **Cause:** A code works once. It was usually already exchanged: the user refreshed the callback page or went back to it, or your app handled the same callback twice. **Fix:** Exchange each code once, then redirect away from the callback URL so a refresh doesn’t replay it. If an exchange fails, start a new login rather than retrying the code. ### `invalid_client` [Section titled “invalid_client”](#invalid_client) You fix ```json {"error":"invalid_client","error_description":"invalid client_id / client_secret"} ``` **Cause:** The client secret doesn’t match the client ID, often because it’s from another environment or was replaced. **Fix:** Use the client ID and secret from the same environment. After you generate a new secret, update it wherever your app is deployed. ## Logins that start at the IdP [Section titled “Logins that start at the IdP”](#logins-that-start-at-the-idp) ### `invalid_idp_initiated_sso` [Section titled “invalid_idp_initiated_sso”](#invalid_idp_initiated_sso) You fix ```text error=invalid_idp_initiated_sso error_description=Initiate-login URL is not configured for the environment ``` **Cause:** A user started from their IdP’s dashboard, such as an Okta app tile, and your production environment has no initiate login URL. A development environment falls back to a Scalekit page instead, so this often shows up first after go-live. **Fix:** Build an initiate login endpoint that accepts a `GET` request, and register it under **Authentication** > **Redirect URLs** > **Initiate login URL**; see [IdP-initiated SSO](/sso/guides/idp-init-sso/). Test it with the SSO simulator’s **IDP Initiated SSO** option. Until it’s live, ask the customer’s users to start from your app’s login page. ## Problems at the identity provider [Section titled “Problems at the identity provider”](#problems-at-the-identity-provider) ### `invalid_in_response_to` [Section titled “invalid_in_response_to”](#invalid_in_response_to) You fix **Cause:** The SAML response doesn’t match a login Scalekit started in this browser. Scalekit tracks each SAML login with a short-lived cookie, which is lost when the app opens the login in an embedded web view, when the user runs two logins at once in the same browser, or when they take several minutes at the IdP. **Fix:** Open SSO logins in the system browser, not an embedded web view, one at a time. A user who sees this once can start the login again. ### `invalid_saml_metadata` [Section titled “invalid_saml_metadata”](#invalid_saml_metadata) IT admin fixes **Cause:** Scalekit can’t use the IdP’s SAML metadata or signing certificate, so logins for that connection fail. The most common cause is a signing certificate that was uploaded by hand and has expired. **Fix:** Your customer’s IT admin uploads the IdP’s current signing certificate, or switches the connection to a metadata URL, which picks up new certificates when the IdP rotates them. See [Certificate expiry and rotation](/sso/guides/security-and-compliance/#certificate-expiry-and-rotation). ### `mandatory_attribute_missing` [Section titled “mandatory_attribute_missing”](#mandatory_attribute_missing) IT admin fixes **Cause:** The IdP didn’t send an attribute Scalekit needs, such as the user’s email address or, for SAML, a `NameID`. The `error_description` names it. **Fix:** Your customer’s IT admin maps the attribute in their IdP’s app settings, then checks it with **Test Connection** in the [admin portal](/authenticate/sso/admin-portal/). ### The user’s name is empty [Section titled “The user’s name is empty”](#the-users-name-is-empty) IT admin fixes **Cause:** The login succeeds, but the profile has no `givenName` or `familyName`, so your app shows a blank name or `undefined undefined`. The IdP sends only the email address. **Fix:** Your customer’s IT admin maps the first and last name attributes in their IdP, for example in Okta’s attribute statements, and checks them with **Test Connection** in the admin portal. In your app, fall back to the email address when the name is empty. ## Admin portal [Section titled “Admin portal”](#admin-portal) ### The admin portal loads a blank page [Section titled “The admin portal loads a blank page”](#the-admin-portal-loads-a-blank-page) IT admin fixes **Cause:** The portal works for you but is blank for your customer, because their network blocks the files it loads. **Fix:** Your customer’s IT admin allows your Scalekit environment’s domain, or your [custom domain](/authenticate/sso/custom-domain/) if you use one, and Google Fonts (`fonts.googleapis.com` and `fonts.gstatic.com`). ## Still stuck [Section titled “Still stuck”](#still-stuck) Find the login under **Logs** in the dashboard: a failed login has the status **Failure** and the error details. When you contact support, include the login’s time, the organization ID and the `error` and `error_description` values. ## Next [Section titled “Next”](#next) * [SSO error reference](/sso/reference/sso-integration-errors/): the error codes your callback can receive and how to resolve them. * [Production readiness checklist](/sso/guides/launch-checklist/): what to check before your first customer goes live. --- # DOCUMENT BOUNDARY --- # SCIM provisioning code samples > Code samples demonstrating SCIM provisioning examples and integration patterns for user and group management ### [Handle SCIM webhooks](https://github.com/scalekit-inc/nextjs-example-apps/tree/main/webhook-events) [Process SCIM directory updates in Next.js. Example shows how to verify webhook signatures and sync user data](https://github.com/scalekit-inc/nextjs-example-apps/tree/main/webhook-events) ### [Embed admin portal](https://github.com/scalekit-inc/nodejs-example-apps/tree/main/embed-admin-portal-sample) [Securely embed the Scalekit Admin Portal via iframe. Node.js example for managing directory sync and organizational settings](https://github.com/scalekit-inc/nodejs-example-apps/tree/main/embed-admin-portal-sample) --- # DOCUMENT BOUNDARY --- # Automatically assign roles > Automatically assign roles to users in your application by mapping directory provider groups to application roles using Scalekit Manually assigning roles to users in your application consumes time and creates room for errors for your customers (usually, administrators). Scalekit monitors role changes in connected directories and notifies your application through webhooks. You use the event payload to keep user roles in your application in sync with directory groups in near real time. ## How group-based role assignment works [Section titled “How group-based role assignment works”](#how-group-based-role-assignment-works) Organization administrators commonly manage varying access levels by grouping users in their directory. For example, to manage access levels to GitHub, they create groups for each role and assign users to those groups. In this case a **Maintainer** group includes all the users who should have maintainer access to the repository. ![Group-based role assignment: directory groups such as Engineering and Managers map through Scalekit to roles such as Editor and Admin in your app](/d2/docs/directory/guides/group-based-role-assignment-0.svg) This enables your application to take necessary actions such as creating or modifying user roles as directed by the organization’s administrators. When an administrator deletes a group from the directory, Scalekit removes that group from every member’s group list and recalculates each member’s role from their remaining group memberships. This happens even for users who belong to multiple mapped groups, so deleting one group never leaves a stale role or membership behind for a user who is still a member of other groups. ## Set up automatic role assignment [Section titled “Set up automatic role assignment”](#set-up-automatic-role-assignment) To enable administrators to map directory groups to roles in your app, complete these steps: 1. Open the Scalekit dashboard. 2. Go to **Roles & Permissions**. 3. Use the **Roles** and **Permissions** sections to configure your application’s authorization model. 4. Register your app’s roles and permissions so Scalekit can reference them in mappings and webhook events. Select **Add role** to create a new role. Choose clear display names and descriptions for your roles. This helps customers understand and align the roles with the access levels they already maintain in their directory. ![Scalekit roles configuration page showing list of application roles](/.netlify/images?url=_astro%2Fadd-role-page.CgXDutLo.png\&w=3024\&h=1612\&dpl=6aedac7ec39c4cadbcd1959e) The roles page lists a couple of sample roles by default. You can edit or remove these and add new roles that match your application’s authorization model. ![Scalekit roles list showing default and custom roles](/.netlify/images?url=_astro%2Fdefault-roles.DC1cIuRF.png\&w=3200\&h=1612\&dpl=6aedac7ec39c4cadbcd1959e) Specify the default roles your app wants to assign to the organization creator and to members who belong to the same organization. All added roles are available for you to select as default roles. ![Scalekit default roles configuration for creators and members](/.netlify/images?url=_astro%2Fdefault-roles.DC1cIuRF.png\&w=3200\&h=1612\&dpl=6aedac7ec39c4cadbcd1959e) ### Connect organization groups to app roles [Section titled “Connect organization groups to app roles”](#connect-organization-groups-to-app-roles) After you create roles, they represent the roles in your app that you want directory groups to control. Users receive role assignments in your app based on the groups they belong to in their directory. You can set up this mapping in two ways: 1. Configure mappings in the Scalekit dashboard on behalf of organization administrators. Select the organization and go to the **SCIM provisioning** tab. 2. Share the [admin portal link](/directory/admin-portal/#generate-shareable-portal-link) with organization administrators so they can configure the mappings themselves. Scalekit automatically displays mapping options in both the Scalekit dashboard and the admin portal. This allows administrators to connect organization groups to app roles without custom logic in your application. ![Mapping directory groups to application roles in Scalekit](/.netlify/images?url=_astro%2F2.CqGIp9Zu.png\&w=2010\&h=1092\&dpl=6aedac7ec39c4cadbcd1959e) ## Handle role update events [Section titled “Handle role update events”](#handle-role-update-events) Scalekit continuously monitors updates from your customers’ directory providers and sends event payloads to your application through a registered webhook endpoint. To set up these endpoints and manage subscriptions, use the **Webhooks** option in the Scalekit dashboard. Listen for the `organization.directory.user_updated` event to determine a user’s roles from the payload. Scalekit automatically includes role information that is relevant to your app, based on the roles you configured in the Scalekit dashboard. * Node.js Create a webhook endpoint for role updates ```javascript 1 // Webhook endpoint to receive directory role updates 2 app.post('/webhook', async (req, res) => { 3 // Extract event data from the webhook payload 4 const event = req.body; 5 const { email, roles } = event.data; 6 7 console.log('Received directory role update for:', email); 8 9 // Extract role_name from the roles array, if present 10 const roleName = Array.isArray(roles) && roles.length > 0 ? roles[0].role_name : null; 11 console.log('Role name received:', roleName); 12 13 // Business logic: update user role and permissions in your app 14 if (roleName) { 15 await assignRole(roleName, email); 16 console.log('Updated access for user:', email); 17 } 18 19 res.status(201).json({ 20 message: 'Role processed', 21 }); 22 }); ``` * Python Create a webhook endpoint for role updates ```python 1 import json 2 from fastapi import FastAPI, Request 3 from fastapi.responses import JSONResponse 4 5 app = FastAPI() 6 7 8 @app.post("/webhook") 9 async def api_webhook(request: Request): 10 # Parse request body from the webhook payload 11 body = await request.body() 12 payload = json.loads(body.decode()) 13 14 # Extract user data 15 user_roles = payload["data"].get("roles", []) 16 user_email = payload["data"].get("email") 17 18 print("User roles:", user_roles) 19 print("User email:", user_email) 20 21 # Business logic: assign role in your app 22 if user_roles and user_email: 23 await assign_role(user_roles[0], user_email) 24 25 return JSONResponse( 26 status_code=201, 27 content={"message": "Role processed"}, 28 ) ``` * Java Create a webhook endpoint for role updates ```java 1 @PostMapping("/webhook") 2 public ResponseEntity> webhook(@RequestBody String body, @RequestHeader Map headers) { 3 ObjectMapper mapper = new ObjectMapper(); 4 5 try { 6 JsonNode node = mapper.readTree(body); 7 JsonNode roles = node.get("data").get("roles"); 8 String email = node.get("data").get("email").asText(); 9 10 System.out.println("Roles: " + roles); 11 System.out.println("Email: " + email); 12 13 // TODO: Add role to user in your application 14 15 Map responseBody = new HashMap<>(); 16 responseBody.put("message", "Role processed"); 17 return ResponseEntity.status(HttpStatus.CREATED).body(responseBody); 18 } catch (IOException e) { 19 return ResponseEntity.status(HttpStatus.BAD_REQUEST).build(); 20 } 21 } ``` * Go Create a webhook endpoint for role updates ```go 1 mux.HandleFunc("POST /webhook", func(w http.ResponseWriter, r *http.Request) { 2 // Read request body from the webhook payload 3 bodyBytes, err := io.ReadAll(r.Body) 4 if err != nil { 5 http.Error(w, err.Error(), http.StatusBadRequest) 6 return 7 } 8 9 // Parse webhook payload 10 var body struct { 11 Data map[string]interface{} `json:"data"` 12 } 13 14 if err := json.Unmarshal(bodyBytes, &body); err != nil { 15 http.Error(w, err.Error(), http.StatusBadRequest) 16 return 17 } 18 19 // Extract user data 20 roles, _ := body.Data["roles"] 21 email, _ := body.Data["email"] 22 23 fmt.Println("Roles:", roles) 24 fmt.Println("Email:", email) 25 26 w.WriteHeader(http.StatusCreated) 27 _, _ = w.Write([]byte(`{"message":"Role processed"}`)) 28 }) ``` Refer to the list of [directory webhook events](/directory/reference/directory-events/) you can subscribe to for more event types. --- # DOCUMENT BOUNDARY --- # Production readiness checklist > A focused checklist for launching your Scalekit SCIM provisioning integration, based on core enterprise authentication launch checks. As you prepare to launch SCIM provisioning to production, you should confirm that your configuration satisfies the SCIM-specific items from the authentication launch checklist. This page extracts the SCIM provisioning items from the main authentication [production readiness checklist](/authenticate/launch-checklist/) and organizes them for your directory rollout. **Verify production environment configuration** Confirm that your environment URL (`SCALEKIT_ENVIRONMENT_URL`), client ID (`SCALEKIT_CLIENT_ID`), and client secret (`SCALEKIT_CLIENT_SECRET`) are correctly configured for your production environment and match your production Scalekit dashboard settings. **Configure SCIM webhook endpoints** Configure webhook endpoints to receive SCIM events in your production environment, and ensure they use HTTPS and correct domain configuration. **Verify webhook security with signature validation** Implement signature validation for incoming SCIM webhooks so only Scalekit can trigger provisioning changes. See [webhook best practices](/guides/webhooks-best-practices/) for guidance. **Test user provisioning, updates, and deprovisioning** Test user provisioning flows (create), deprovisioning flows (deactivate or delete), and user profile updates to ensure your application responds correctly to each event type. **Validate group-based role assignment** Set up group-based role assignment and synchronization, and verify that group membership changes in the identity provider correctly map to roles and permissions in your application. **Handle duplicate and invalid data scenarios** Test error scenarios such as duplicate users, conflicting identifiers, and invalid data payloads so your integration fails safely and surfaces actionable errors. **Align SCIM with user and organization models** Confirm that your SCIM implementation matches your user and organization data model, including how you represent organizations, teams, and role assignments in your system. **Finalize admin portal configuration for directory admins** Ensure directory admins can configure SCIM connections in the admin portal, and that your branding and access controls are correct for enterprise customers. --- # DOCUMENT BOUNDARY --- # Onboard enterprise customers > Complete workflow for enabling SCIM provisioning and self-serve directory sync configuration for your enterprise customers Enterprise provisioning with SCIM enables you to automatically create, update, and deactivate users in your application based on changes in your customers’ directory providers such as Okta, Microsoft Entra ID, or Google Workspace. This gives enterprise customers centralized user lifecycle management while reducing manual administration and access drift. ![How Scalekit connects your application to enterprise directories and identity providers](/.netlify/images?url=_astro%2Fhow-scalekit-connects.CrZX8E30.png\&w=5776\&h=1924\&dpl=6aedac7ec39c4cadbcd1959e) This guide walks you through the complete workflow for onboarding enterprise customers with SCIM provisioning. You’ll learn how to create organizations, provide admin portal access, enable directory sync, and verify that provisioning works end to end. Before onboarding enterprise customers with provisioning, ensure you have completed the [SCIM quickstart](/directory/scim/quickstart/) to set up basic directory sync in your application. ## Table of contents * [Create organization](#create-organization) * [Provide admin portal access](#provide-admin-portal-access) * [Customer configures SCIM provisioning](#customer-configures-scim-provisioning) * [Verify provisioning and run test sync](#verify-provisioning-and-run-test-sync) 1. ## Create organization Create an organization in Scalekit to represent your enterprise customer: * Log in to the [Scalekit dashboard](https://app.scalekit.com) * Navigate to **Dashboard > Organizations** * Click **Create Organization** * Enter the organization name and relevant details * Save the organization Each organization in Scalekit represents one of your enterprise customers and can have its own directory sync settings, SSO configuration, and domain associations. 2. ## Provide admin portal access Give your customer’s IT administrator access to the self-serve admin portal to configure their directory and SCIM connection. Scalekit provides two integration methods: **Option 1: Share a no-code link** Quick setup Generate and share a link to the admin portal: * Select the organization from **Dashboard > Organizations** * Click **Generate link** in the organization overview * Share the link with your customer’s IT admin via email, Slack, or your preferred channel The link remains valid for 7 days and can be revoked anytime from the dashboard. **Link properties:** | Property | Details | | -------------- | ------------------------------------------------------------------------------- | | **Expiration** | Links expire after 7 days | | **Revocation** | Revoke links anytime from the dashboard | | **Sharing** | Share via email, Slack, or any preferred channel | | **Security** | Anyone with the link can view and update the organization’s connection settings | The generated link follows this format: Portal link example ```http https://your-app.scalekit.dev/magicLink/2cbe56de-eec4-41d2-abed-90a5b82286c4_p ``` Security consideration Treat portal links as sensitive credentials. Anyone with the link can view and modify the organization’s SSO and SCIM configuration. **Option 2: Embed the portal** Seamless experience Embed the admin portal directly in your application so customers can configure SCIM provisioning and SSO without leaving your interface. The portal link must be generated programmatically on each page load for security. Each generated link is single-use and expires after 1 minute, though once loaded, the session remains active for up to 6 hours. * Node.js ```bash npm install @scalekit-sdk/node ``` * Python ```sh pip install scalekit-sdk-python ``` * Go ```sh go get -u github.com/scalekit-inc/scalekit-sdk-go/v2 ``` * Java The Java SDK is published to Scalekit’s Maven repository, `https://us-maven.pkg.dev/scalekit-public/java`. Add it to your build next to Maven Central. It needs no credentials. If your builds download dependencies only through a mirror such as Nexus or Artifactory, add this URL to the mirror instead. For Maven, add the `` and `` entries to the matching sections of your existing `pom.xml`. ```groovy // Gradle: build.gradle repositories { mavenCentral() maven { url "https://us-maven.pkg.dev/scalekit-public/java" } } dependencies { implementation "com.scalekit:scalekit-sdk-java:2.6.1" } ``` ```xml scalekit https://us-maven.pkg.dev/scalekit-public/java com.scalekit scalekit-sdk-java 2.6.1 ``` ### Generate portal link Use the Scalekit SDK to generate a unique, embeddable admin portal link for an organization. Call this API endpoint each time you render the page containing the iframe: * Node.js Express.js ```javascript import { Scalekit } from '@scalekit-sdk/node'; const scalekit = new Scalekit( process.env.SCALEKIT_ENVIRONMENT_URL, process.env.SCALEKIT_CLIENT_ID, process.env.SCALEKIT_CLIENT_SECRET, ); async function generatePortalLink(organizationId) { const link = await scalekit.organization.generatePortalLink(organizationId); return link.location; // Use as iframe src } ``` * Python Flask ```python from scalekit import Scalekit import os scalekit_client = Scalekit( environment_url=os.environ.get("SCALEKIT_ENVIRONMENT_URL"), client_id=os.environ.get("SCALEKIT_CLIENT_ID"), client_secret=os.environ.get("SCALEKIT_CLIENT_SECRET") ) def generate_portal_link(organization_id): link = scalekit_client.organization.generate_portal_link(organization_id) return link.location # Use as iframe src ``` * Go Gin ```go 1 import ( 2 "context" 3 "os" 4 5 "github.com/scalekit/sdk-go" 6 ) 7 8 scalekitClient := scalekit.New( 9 os.Getenv("SCALEKIT_ENVIRONMENT_URL"), 10 os.Getenv("SCALEKIT_CLIENT_ID"), 11 os.Getenv("SCALEKIT_CLIENT_SECRET"), 12 ) 13 14 func generatePortalLink(organizationID string) (string, error) { 15 ctx := context.Background() 16 link, err := scalekitClient.Organization().GeneratePortalLink(ctx, organizationID) 17 if err != nil { 18 return "", err 19 } 20 return link.Location, nil // Use as iframe src 21 } ``` * Java Spring Boot ```java 1 import com.scalekit.client.Scalekit; 2 import com.scalekit.client.models.Link; 3 import com.scalekit.client.models.Feature; 4 import java.util.Arrays; 5 6 Scalekit scalekitClient = new Scalekit( 7 System.getenv("SCALEKIT_ENVIRONMENT_URL"), 8 System.getenv("SCALEKIT_CLIENT_ID"), 9 System.getenv("SCALEKIT_CLIENT_SECRET") 10 ); 11 12 public String generatePortalLink(String organizationId) { 13 Link portalLink = scalekitClient.organizations() 14 .generatePortalLink(organizationId, Arrays.asList(Feature.sso, Feature.dir_sync)); 15 return portalLink.getLocation(); // Use as iframe src 16 } ``` The API returns a JSON object with the portal link. Use the `location` property as the iframe `src`: API response ```json { "id": "8930509d-68cf-4e2c-8c6d-94d2b5e2db43", "location": "https://random-subdomain.scalekit.dev/magicLink/8930509d-68cf-4e2c-8c6d-94d2b5e2db43", "expireTime": "2024-10-03T13:35:50.563013Z" } ``` Embed portal in iframe ```html ``` Embed the portal in your application’s settings or admin section where customers manage authentication configuration. Listen for UI events from the embedded portal to respond to configuration changes, such as when directory sync is enabled, provisioning is tested, or the session expires. See the [Admin portal UI events reference](/reference/admin-portal/ui-events/) for details on handling these events. ### Configuration and session | Setting | Requirement | | --------------------- | ----------------------------------------------------------------------------- | | **Redirect URI** | Add your application domain at **Dashboard > Developers > API Configuration** | | **iframe attributes** | Include `allow="clipboard-write"` for copy-paste functionality | | **Dimensions** | Minimum recommended height: 600px | | **Link expiration** | Generated links expire after 1 minute if not loaded | | **Session duration** | Portal session remains active for up to 6 hours once loaded | | **Single-use** | Each generated link can only be used once to initialize a session | 3. ## Customer configures SCIM provisioning After receiving admin portal access, your customer’s IT administrator: * Opens the admin portal (via shared link or embedded iframe) * Selects their directory integration (Okta, Microsoft Entra ID, Google Workspace, etc.) * Follows the provider-specific SCIM or directory sync setup guide * Enters the required configuration (SCIM endpoint URL, access token, and any required headers) * Tests user provisioning from their directory to your application * Activates the SCIM connection Once configured, the directory sync or SCIM connection appears as active in your organization’s settings. 4. ## Verify provisioning and run test sync After SCIM provisioning is configured, verify that user and group changes flow correctly from the customer’s directory into your application. This ensures your enterprise onboarding is reliable before rolling out broadly. To verify provisioning: * Create a test user in the customer’s directory and assign them to the appropriate groups or applications * Confirm that the user appears in your application’s organization with the expected attributes (name, email, roles, and status) * Update the user’s attributes or group memberships in the directory and verify that changes propagate to your application * Deactivate or delete the test user in the directory and ensure their access is revoked in your application ## Customize the admin portal Match the admin portal to your brand identity. Configure branding at **Dashboard > Settings > Branding**: | Option | Description | | ---------------- | --------------------------------------------------------- | | **Logo** | Upload your company logo (displayed in the portal header) | | **Accent color** | Set the primary color to match your brand palette | | **Favicon** | Provide a custom favicon for browser tabs | For additional customization options including custom domains, see the [Custom domain guide](/guides/custom-domain/). --- # DOCUMENT BOUNDARY --- # Review SCIM protocol > Learn about core components, resources, schemas, and real-world implementation scenarios for identity management across cloud applications through SCIM System for Cross-domain Identity Management (SCIM) is an [open standard API specification](https://datatracker.ietf.org/doc/html/rfc7643#section-2) designed to manage identities across cloud applications easily and scalably. The specification suite builds upon experience with existing schemas and deployments, emphasizing: * Simplicity of development and integration * Application of existing authentication, authorization, and privacy models Its intent is to reduce the cost and complexity of user management operations by providing: * A common user schema * An extension model; e.g., enterprise user * Binding documents to provide patterns for exchanging this schema using HTTP ## SCIM protocol: Key components [Section titled “SCIM protocol: Key components”](#scim-protocol-key-components) SCIM is a HTTP based protocol and uses structured [JSON](https://datatracker.ietf.org/doc/html/rfc7159) payloads to exchange resource information between the SCIM client and service provider. To identify the SCIM protocol resources, the `application/scim+json` media type is used. ### SCIM service provider [Section titled “SCIM service provider”](#scim-service-provider) SCIM service provider is any business application that provisions users and groups by synchronizing the changes made in a SCIM client, including creates, updates, and deletes. The synchronization enables end users to have seamless access to the business application for which they’re assigned, with up-to-date profiles and permissions. Scalekit acts as the SCIM service provider on your behalf and integrates with your customer’s identity providers or directory providers (e.g. Okta, Azure AD, Google Workspace, etc.) to provision users and groups. ### SCIM client [Section titled “SCIM client”](#scim-client) SCIM client facilitates provisioning, or managing user lifecycle events, through SCIM endpoints exposed by the SCIM service provider. Identity providers and HRMS act as very popular SCIM clients as they are treated as the source of truth for user identity data. Some of the most common SCIM clients are [Okta](https://www.okta.com), [Microsoft Entra ID (aka Azure AD)](https://www.microsoft.com/en-in/security/business/identity-access/microsoft-entra-id). ### SCIM endpoints [Section titled “SCIM endpoints”](#scim-endpoints) SCIM endpoints are the entry points to the SCIM API. They are the endpoints that the SCIM client will call to provision users and groups. The following are the most popular SCIM endpoints that any SCIM service provider should support: * `/Users` * `/Groups` ### SCIM methods [Section titled “SCIM methods”](#scim-methods) As SCIM is built on top of REST, SCIM methods are the HTTP methods that are used to perform CRUD operations on the SCIM resources. The following are the most common SCIM methods: * GET * POST * PUT * PATCH * DELETE ### SCIM authentication [Section titled “SCIM authentication”](#scim-authentication) SCIM uses OAuth 2.0 bearer token authentication to authenticate requests to the SCIM API. The token is a string that is used to authenticate the SCIM API requests to the SCIM service provider. The token is passed in the HTTP Authorization header using the Bearer scheme. ## SCIM resources [Section titled “SCIM resources”](#scim-resources) SCIM resources are the core building blocks of the SCIM protocol. They represent entities such as users, groups, and organizational units. Each resource has a set of attributes that describe the entity. While SCIM user resource has the basic attributes of a user like email address, phone number, and name, it is extensible by defining new JSON schemas that a service provider can choose to implement. An enterprise user is an example of a SCIM user extension resource. Enterprise user resource has attributes such as employee number, department, and manager which are valuable for enterprise implementation of user management using SCIM v2. Example SCIM user representation ```json 1 { 2 "schemas": ["urn:ietf:params:scim:schemas:core:2.0:User"], 3 "userName": "bjensen", 4 "name": { 5 "givenName": "Barbara", 6 "familyName": "Jensen" 7 }, 8 "emails": [ 9 { 10 "value": "bjensen@example.com", 11 "type": "work", 12 "primary": true 13 } 14 ], 15 "entitlements": [ 16 { 17 "value": "Employee", 18 "type": "role" 19 } 20 ] 21 } ``` ### SCIM schema [Section titled “SCIM schema”](#scim-schema) SCIM schema is the core of the SCIM protocol. It is a JSON schema that defines the structure of the SCIM resources. The following are the most common SCIM schemas: * [Core SCIM user schema](https://datatracker.ietf.org/doc/html/rfc7643#section-4.1) * [Enterprise user schema](https://datatracker.ietf.org/doc/html/rfc7643#section-4.3) * [Group schema](https://datatracker.ietf.org/doc/html/rfc7643#section-4.2) ## Putting everything together [Section titled “Putting everything together”](#putting-everything-together) Now that you have a high level understanding of the SCIM protocol and different components involved, let’s put everything together to take a scenario of how SCIM protocol facilitates user provisioning from an identity provider to a SCIM service provider like Scalekit. ### Scenario: New employee onboarding [Section titled “Scenario: New employee onboarding”](#scenario-new-employee-onboarding) 1. ACME Inc. hires a new employee, John Doe. 2. ACME Inc. adds John Doe to their Okta directory. 3. Okta send a SCIM `POST /Users` request to a pre-registered SCIM service provider (your B2B application) with John Doe’s information as per the SCIM protocol. 4. You authenticate the request using the OAuth 2.0 bearer token authentication & validate the request payload. 5. You provision John Doe as a new user in your B2B application using the user payload. ### Scenario: Employee termination [Section titled “Scenario: Employee termination”](#scenario-employee-termination) 1. ACME Inc. terminates John Doe’s employment. 2. ACME Inc. removes John Doe from their Okta directory. 3. Okta send a SCIM `DELETE /Users/john.doe` request to a pre-registered SCIM service provider (your B2B application) as per the SCIM protocol. 4. You authenticate the request using the OAuth 2.0 bearer token authentication & validate the request payload. 5. You deactivate John Doe as an existing user in your B2B application using the user payload. ### Scenario: Employee transfer [Section titled “Scenario: Employee transfer”](#scenario-employee-transfer) 1. ACME Inc. transfers John Doe to a different department. 2. ACME Inc. updates John Doe’s information in their Okta directory. 3. Okta send a SCIM `PATCH /Users/john.doe` request to a pre-registered SCIM service provider (your B2B application) as per the SCIM protocol. 4. You authenticate the request using the OAuth 2.0 bearer token authentication & validate the request payload. 5. You update John Doe’s information in your B2B application using the user payload. SCIM create user request ```http 1 POST /Users HTTP/1.1 2 Host: yourapp.scalekit.com/directory/dir_12442/scim/v2 3 Accept: application/scim+json 4 Content-Type: application/scim+json 5 Authorization: Bearer YOUR_SCIM_API_TOKEN 6 7 { 8 "schemas":["urn:ietf:params:scim:schemas:core:2.0:User"], 9 "userName":"bjensen", 10 "externalId":"bjensen", 11 "name":{ 12 "formatted":"Ms. Barbara J Jensen III", 13 "familyName":"Jensen", 14 "givenName":"Barbara" 15 } 16 } ``` ## Scalekit’s SCIM implementation [Section titled “Scalekit’s SCIM implementation”](#scalekits-scim-implementation) Scalekit’s SCIM implementation is built upon the principles of simplicity, security, and scalability. It provides a normalized implementation of the SCIM protocol across different identity providers & directory providers. This allows you to focus on integrating with Scalekit’s API & leave the complexities of SCIM protocol implementation to us. While not all directory providers implement SCIM or support all SCIM features, Scalekit aims to abstract these complexities & provide a seamless experience for provisioning users and groups. ### Webhooks [Section titled “Webhooks”](#webhooks) Scalekit supports webhooks as a mechanism to send real-time updates to your application about user provisioning and deprovisioning events to your application as and when there are changes detected in your customer’s SCIM compliant directory providers. We also normalize the webhook payloads across different directory providers to ensure that you can focus on building your application without having to worry about the nuances of each directory provider’s SCIM implementations. --- # DOCUMENT BOUNDARY --- # Provision Supabase users with SCIM > Create, update and block Supabase Auth users from your customers' directories, using Scalekit's SCIM webhooks and the Supabase admin API. Your enterprise customers sign in to your app with SSO, and their IT teams now want to manage who has access from their directory, such as Okta or Microsoft Entra ID, instead of inviting and removing people by hand. With SCIM, the directory tells Scalekit about each change, Scalekit sends your app a webhook, and a small handler applies the change to Supabase Auth with the admin API. By the end: * Users your customers add to their directory are created in Supabase, and their details stay in sync. * Users your customers deactivate are blocked in Supabase, so they can’t sign in or refresh their session. Reactivated users are unblocked. To also let these users sign in through their company’s identity provider, see [Add SSO to Supabase Auth](/guides/integrations/auth-systems/supabase/). ## Before you start [Section titled “Before you start”](#before-you-start) * A Supabase project and its secret key (`sb_secret_…`) or legacy service role key. Run the handler on your server; never ship either key to a browser. * Your Scalekit environment URL, client ID and client secret, from **Developers** > **Settings** > **API Credentials** in the Scalekit dashboard. * An organization in Scalekit with a directory connected, and a webhook endpoint subscribed to the directory user events. Copy the endpoint’s signing secret (`whsec_…`). See [Set up SCIM provisioning](/directory/scim/quickstart/). ## What Scalekit sends [Section titled “What Scalekit sends”](#what-scalekit-sends) Each change in the directory reaches your handler as one of three events: | Event | When | | ------------------------------------- | ------------------------------------------------------ | | `organization.directory.user_created` | A user is added, or a deactivated user is reactivated. | | `organization.directory.user_updated` | An active user’s details change. | | `organization.directory.user_deleted` | A user is deactivated or removed. | ## Map directory users to Supabase users [Section titled “Map directory users to Supabase users”](#map-directory-users-to-supabase-users) The handler needs to know which Supabase user each directory user is. A table keeps that mapping. The first time the directory sends someone, a function looks for an existing Supabase user with the same email in the same Scalekit organization: someone who already signed in through that organization’s SSO connection, or someone the handler created for it before. The handler marks the users it creates in `app_metadata`, which only the admin API can change. Anyone else with that email is left alone, such as a user who signed up with a password or one from another organization. Otherwise, someone who registered an employee’s email first could take over their account. In that case `createUser` fails with `email_exists` and the handler returns `500`, so you can sort it out. Run this SQL in the Supabase **SQL Editor**: directory_users.sql ```sql 1 create table public.directory_users ( 2 directory_user_id text primary key, 3 supabase_user_id uuid not null references auth.users (id) on delete cascade 4 ); 5 alter table public.directory_users enable row level security; 6 revoke all on table public.directory_users from anon, authenticated; 7 grant select, insert, update on table public.directory_users to service_role; 8 9 create function public.organization_user_id_by_email( 10 p_email text, 11 p_organization_id text, 12 p_directory_user_id text 13 ) 14 returns uuid 15 language sql 16 stable 17 security definer 18 set search_path = '' 19 as $$ 20 select u.id 21 from auth.users u 22 where lower(u.email) = lower(p_email) 23 and ( 24 -- Signed in through the organization's SSO connection 25 exists ( 26 select 1 from auth.identities i 27 where i.user_id = u.id 28 and i.provider = 'custom:scalekit' 29 and i.identity_data -> 'custom_claims' ->> 'oid' = p_organization_id 30 ) 31 -- Created by the handler for the organization, for this directory user 32 -- or one it replaced. Only the admin API can set app_metadata. 33 or ( 34 u.raw_app_meta_data ->> 'organization_id' = p_organization_id 35 and ( 36 u.raw_app_meta_data ->> 'directory_user_id' = p_directory_user_id 37 or exists (select 1 from public.directory_users d where d.supabase_user_id = u.id) 38 ) 39 ) 40 ) 41 limit 1; 42 $$; 43 revoke execute on function public.organization_user_id_by_email(text, text, text) from public, anon, authenticated; 44 grant execute on function public.organization_user_id_by_email(text, text, text) to service_role; ``` ## Run the webhook handler [Section titled “Run the webhook handler”](#run-the-webhook-handler) The handler checks each webhook’s signature, then creates, updates or blocks the user: scim-webhook.mjs ```javascript 1 import 'dotenv/config' 2 import express from 'express' 3 import { Scalekit } from '@scalekit-sdk/node' 4 import { createClient } from '@supabase/supabase-js' 5 6 const scalekit = new Scalekit( 7 process.env.SCALEKIT_ENVIRONMENT_URL, 8 process.env.SCALEKIT_CLIENT_ID, 9 process.env.SCALEKIT_CLIENT_SECRET, 10 ) 11 const supabase = createClient(process.env.SUPABASE_URL, process.env.SUPABASE_SERVICE_ROLE_KEY) 12 13 // About 100 years: Supabase has no permanent ban, so use a very long one 14 const BLOCKED = '876000h' 15 16 async function findSupabaseUserId(directoryUser, organizationId) { 17 const { data, error } = await supabase 18 .from('directory_users') 19 .select('supabase_user_id') 20 .eq('directory_user_id', directoryUser.id) 21 .maybeSingle() 22 if (error) throw error 23 if (data) return data.supabase_user_id 24 25 // The user may already exist, for example because they signed in with SSO first 26 const { data: id, error: rpcError } = await supabase.rpc('organization_user_id_by_email', { 27 p_email: directoryUser.email, 28 p_organization_id: organizationId, 29 p_directory_user_id: directoryUser.id, 30 }) 31 if (rpcError) throw rpcError 32 return id 33 } 34 35 async function upsertUser(directoryUser, organizationId) { 36 const attributes = { 37 email: directoryUser.email, 38 user_metadata: { 39 given_name: directoryUser.given_name, 40 family_name: directoryUser.family_name, 41 }, 42 // Lets a retry find this user if saving the mapping below fails 43 app_metadata: { organization_id: organizationId, directory_user_id: directoryUser.id }, 44 } 45 46 let id = await findSupabaseUserId(directoryUser, organizationId) 47 if (id) { 48 // Also lifts the block on a user the directory reactivates 49 const { error } = await supabase.auth.admin.updateUserById(id, { 50 ...attributes, 51 email_confirm: true, 52 ban_duration: 'none', 53 }) 54 if (error) throw error 55 } else { 56 const { data, error } = await supabase.auth.admin.createUser({ 57 ...attributes, 58 email_confirm: true, 59 }) 60 if (error) throw error 61 id = data.user.id 62 } 63 64 const { error } = await supabase 65 .from('directory_users') 66 .upsert({ directory_user_id: directoryUser.id, supabase_user_id: id }) 67 if (error) throw error 68 } 69 70 async function blockUser(directoryUser, organizationId) { 71 const id = await findSupabaseUserId(directoryUser, organizationId) 72 if (!id) return 73 const { error } = await supabase.auth.admin.updateUserById(id, { ban_duration: BLOCKED }) 74 if (error) throw error 75 } 76 77 async function handleEvent(event) { 78 switch (event.type) { 79 // Also sent when the directory reactivates a user 80 case 'organization.directory.user_created': 81 return upsertUser(event.data, event.organization_id) 82 case 'organization.directory.user_updated': 83 if (event.data.active === false) return blockUser(event.data, event.organization_id) 84 return upsertUser(event.data, event.organization_id) 85 // Also sent when the directory deactivates a user 86 case 'organization.directory.user_deleted': 87 return blockUser(event.data, event.organization_id) 88 } 89 } 90 91 const app = express() 92 93 app.post('/webhooks/scalekit', express.raw({ type: 'application/json' }), async (req, res) => { 94 const payload = req.body.toString() 95 const headers = { 96 'webhook-id': req.headers['webhook-id'], 97 'webhook-timestamp': req.headers['webhook-timestamp'], 98 'webhook-signature': req.headers['webhook-signature'], 99 } 100 101 try { 102 scalekit.verifyWebhookPayload(process.env.SCALEKIT_WEBHOOK_SECRET, headers, payload) 103 } catch { 104 return res.status(401).json({ error: 'Invalid signature' }) 105 } 106 107 try { 108 await handleEvent(JSON.parse(payload)) 109 return res.status(200).json({ received: true }) 110 } catch (err) { 111 console.error('Failed to process webhook:', err) 112 return res.status(500).json({ error: 'Processing failed' }) 113 } 114 }) 115 116 app.listen(3000, () => console.log('Listening on http://localhost:3000')) ``` Install the packages with `npm install express @scalekit-sdk/node @supabase/supabase-js dotenv`, add `SCALEKIT_WEBHOOK_SECRET` to your `.env` file, and run `node scim-webhook.mjs`. Scalekit retries a webhook that fails, and the handler is safe to run twice, so a retry doesn’t create a second user. Blocking keeps the user’s data, and access tokens issued before the block stay valid until they expire. To delete users instead, call `supabase.auth.admin.deleteUser(id)` in `blockUser`. ## Test provisioning [Section titled “Test provisioning”](#test-provisioning) 1. Expose the handler at a public URL, such as with a tunnel, and set that URL on your webhook endpoint in Scalekit. 2. Add a user to the directory, or assign them to the app in your IdP. 3. In the Supabase **SQL Editor**, look at the users the handler created: ```sql select distinct u.email, u.raw_app_meta_data ->> 'organization_id' as organization_id, u.banned_until from public.directory_users d join auth.users u on u.id = d.supabase_user_id; ``` The new user has your Scalekit organization ID and an empty `banned_until`. 4. Deactivate the user in the directory. Their `banned_until` is now about 100 years in the future, and they can’t sign in. ## Next [Section titled “Next”](#next) * [Add SSO to Supabase Auth](/guides/integrations/auth-systems/supabase/): let these users sign in through their company’s IdP. * [Directory webhooks reference](/directory/reference/directory-events/): the fields in the user events. --- # DOCUMENT BOUNDARY --- # Understanding SCIM Provisioning > The business case for implementing SCIM Scaling organizations utilize a growing array of applications to support their employees’ productivity. To efficiently and securely manage access to these applications, organization administrators employ Directory Providers. These providers automate crucial workflows, such as granting access to new employees or revoking access for departing staff. Directory providers, like Entra ID (formerly Azure Active Directory), serve as the authoritative source for user information and access rights. Organizations expect your application to accommodate their directory provider requirements. Consequently, you must design systems capable of interfacing with various directory providers used by their customers. Scalekit serves as an intermediary component in your B2B application architecture, providing a streamlined interface to access user information programmatically and in real-time. ![User onboarding flow across your app, Scalekit, and directory providers](/.netlify/images?url=_astro%2Fbasics.BBrrKGoZ.png\&w=4260\&h=2200\&dpl=6aedac7ec39c4cadbcd1959e) This solution allows your application to: 1. Automatically determine user roles (e.g., admin, member) 2. Retrieve user access permissions 3. Tailor the user experience accordingly and securely By integrating Scalekit, you can meet enterprise requirements without diverting focus from your core product development. This approach significantly reduces the engineering effort and time typically required to implement compatibility with various directory providers. Explore the compelling reasons to implement SCIM Provisioning in your B2B SaaS app: Implementing SCIM allows you to offer a more attractive, enterprise-grade solution. ## Next steps [Section titled “Next steps”](#next-steps) Now that you understand the importance of directories and how implementing SCIM Provisioning can step up your app to enterprise-grade status, it’s time to put this knowledge into action. Here are some suggested next steps: 1. Dive into our [Quickstart](/directory/scim/quickstart/) guide to learn how to set up SCIM Provisioning for your app. This practical guide will walk you through the implementation process step-by-step. 2. Start small by simulating directory events. This hands-on approach allows you to test and familiarize yourself with the system without affecting live data. 3. Explore our sample apps to picture all the moving components in a typical app. --- # DOCUMENT BOUNDARY --- # Directory events > Explore webhook events related to directory operations in Scalekit, including user and group creation, updates, and deletions. This page documents the webhook events Scalekit sends when an organization’s directory, its users or its groups change. ## Table of contents * [Event envelope](#event-envelope) * [Directory connection events](#directory-connection-events) * [`organization.directory_created`](#organizationdirectory_created) * [`organization.directory_enabled`](#organizationdirectory_enabled) * [`organization.directory_disabled`](#organizationdirectory_disabled) * [`organization.directory_deleted`](#organizationdirectory_deleted) * [Directory user events](#directory-user-events) * [`organization.directory.user_created`](#organizationdirectoryuser_created) * [`organization.directory.user_updated`](#organizationdirectoryuser_updated) * [`organization.directory.user_deleted`](#organizationdirectoryuser_deleted) * [Directory group events](#directory-group-events) * [`organization.directory.group_created`](#organizationdirectorygroup_created) * [`organization.directory.group_updated`](#organizationdirectorygroup_updated) * [`organization.directory.group_deleted`](#organizationdirectorygroup_deleted) *** ## Event envelope Every directory event has the same top-level fields. The event-specific fields are in `data`. Keys can arrive in any order, so parse the body as JSON rather than matching it as text. | Field | Type | Description | | ----------------- | ------ | ---------------------------------------------------------------------------- | | `spec_version` | string | Webhook payload version. Currently `"1"` | | `id` | string | Unique event ID, prefixed with `evt_`. Use it to ignore duplicate deliveries | | `type` | string | Event type, such as `organization.directory.user_created` | | `occurred_at` | string | When the event occurred, in RFC 3339 format | | `environment_id` | string | Environment the event belongs to | | `organization_id` | string | Organization the directory belongs to | | `object` | string | `Directory`, `DirectoryUser` or `DirectoryGroup` | | `data` | object | The directory, user or group. See each event below | ## Directory connection events ### `organization.directory_created` Sent when a directory is created for an organization. A SCIM or LDAP directory is enabled on creation, so `organization.directory_enabled` follows. A POLL directory is created disabled and sends only this event. `data` has four fields only. organization.directory_created ```json { "spec_version": "1", "id": "evt_55136848686612000", "type": "organization.directory_created", "occurred_at": "2025-01-15T08:55:22.702860294Z", "environment_id": "env_27758032200925221", "organization_id": "org_55135410258444802", "object": "Directory", "data": { "directory_type": "SCIM", "id": "dir_55135622825771522", "organization_id": "org_55135410258444802", "provider": "OKTA" } } ``` | Field | Type | Description | | ----------------- | ------ | --------------------------------------- | | `id` | string | Directory ID, prefixed with `dir_` | | `organization_id` | string | Organization that owns the directory | | `directory_type` | string | How the directory syncs, such as `SCIM` | | `provider` | string | Directory provider, such as `OKTA` | ### `organization.directory_enabled` Sent when directory sync is enabled for an organization. organization.directory_enabled ```json 1 { 2 "spec_version": "1", 3 "id": "evt_55136848686613000", 4 "type": "organization.directory_enabled", 5 "occurred_at": "2025-01-15T08:55:22.802860294Z", 6 "environment_id": "env_27758032200925221", 7 "organization_id": "org_55135410258444802", 8 "object": "Directory", 9 "data": { 10 "directory_type": "SCIM", 11 "enabled": true, 12 "id": "dir_55135622825771522", 13 "organization_id": "org_55135410258444802", 14 "provider": "OKTA", 15 "updated_at": "2025-01-15T08:55:22.792993454Z" 16 } 17 } ``` | Field | Type | Description | | ----------------- | ------- | --------------------------------------- | | `id` | string | Directory ID, prefixed with `dir_` | | `organization_id` | string | Organization that owns the directory | | `directory_type` | string | How the directory syncs, such as `SCIM` | | `provider` | string | Directory provider, such as `OKTA` | | `enabled` | boolean | Always `true` on this event | | `updated_at` | string | When the directory was last updated | ### `organization.directory_disabled` Sent when directory sync is disabled for an organization. `data` has four fields only. organization.directory_disabled ```json { "spec_version": "1", "id": "evt_53891640779079756", "type": "organization.directory_disabled", "occurred_at": "2025-01-06T18:45:21.057814Z", "environment_id": "env_53814739859406915", "organization_id": "org_53879494091473415", "object": "Directory", "data": { "directory_type": "SCIM", "id": "dir_53879621145330183", "organization_id": "org_53879494091473415", "provider": "OKTA" } } ``` | Field | Type | Description | | ----------------- | ------ | --------------------------------------- | | `id` | string | Directory ID, prefixed with `dir_` | | `organization_id` | string | Organization that owns the directory | | `directory_type` | string | How the directory syncs, such as `SCIM` | | `provider` | string | Directory provider, such as `OKTA` | ### `organization.directory_deleted` Sent when a directory is deleted. Deleting a directory through the API or dashboard requires disabling it first. Deleting an organization also deletes its directories, enabled or not, and sends this event for each. `data` has four fields only. organization.directory_deleted ```json { "spec_version": "1", "id": "evt_53891640779079900", "type": "organization.directory_deleted", "occurred_at": "2025-01-06T18:50:02.118243Z", "environment_id": "env_53814739859406915", "organization_id": "org_53879494091473415", "object": "Directory", "data": { "directory_type": "SCIM", "id": "dir_53879621145330183", "organization_id": "org_53879494091473415", "provider": "OKTA" } } ``` | Field | Type | Description | | ----------------- | ------ | --------------------------------------- | | `id` | string | Directory ID, prefixed with `dir_` | | `organization_id` | string | Organization that owns the directory | | `directory_type` | string | How the directory syncs, such as `SCIM` | | `provider` | string | Directory provider, such as `OKTA` | ## Directory user events All three user events send the same user object in `data`. * `organization.directory.user_created` is sent when the directory provider creates an active user, or reactivates a deactivated user. * `organization.directory.user_updated` is sent when an active user’s attributes change, or when the user is added to or removed from a group. * `organization.directory.user_deleted` is sent when an active user is deactivated or deleted in the directory provider. `data` carries the last known user record. `active` is `false` when the user was deactivated. Changes to a user who is already inactive send no event. ### Directory user fields The first seven fields are always sent. `roles` is computed by Scalekit and is sent on every user event when your environment has roles. The rest are sent only when the directory provider supplies them. | Field | Type | Description | | -------------------- | -------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `id` | string | Directory user ID, prefixed with `diruser_` | | `organization_id` | string | Organization the user belongs to | | `active` | boolean | Whether the user is active in the directory provider | | `preferred_username` | string | The user’s `userName` from the provider. Empty string if not set | | `dp_id` | string | The user’s `externalId` from the provider. Empty string if not set | | `email` | string or null | Primary email address. `null` if the provider marks no email as primary | | `groups` | array or null | Groups the user belongs to, each with `id` and `name`. `null` if the user is in no groups | | `name` | string | Display name | | `given_name` | string | Given (first) name | | `family_name` | string | Family (last) name | | `nickname` | string | Nickname | | `picture` | string | Profile picture URL | | `phone_number` | string | Work phone number | | `address` | object | The user’s SCIM address of type `work`: `street_address`, `locality`, `state` (from SCIM `region`), `postal_code`, `country` and `formatted` | | `profile` | string | Profile URL | | `locale` | string | Locale | | `zoneinfo` | string | Time zone | | `language` | string | Preferred language | | `title` | string | Job title | | `user_type` | string | User type | | `employee_id` | string | Employee number from the SCIM enterprise extension | | `cost_center` | string | Cost center from the enterprise extension | | `organization` | string | Organization from the enterprise extension | | `division` | string | Division from the enterprise extension | | `department` | string | Department from the enterprise extension | | `manager` | object | The user’s manager, with `id`, `email` and `user_name`, when the manager is also in the directory | | `roles` | array | Scalekit roles assigned through [group-based role assignment](/directory/guides/group-based-role-assignment/), each with `role_name`. An empty array when no role applies | | `dp_roles` | array or null | Roles as sent by the provider, each with `display`, `primary`, `type` and `value`. `null` if the provider sends an empty list | | `entitlements` | array or null | Entitlements as sent by the provider, each with `display`, `primary`, `type` and `value`. `null` if the provider sends an empty list | | `custom_attributes` | object | Custom attributes you mapped for this directory, plus `home_phone_number` and `mobile_phone_number` when the provider sends them | | `raw_attributes` | object | The SCIM user resource as received from the provider | ### `organization.directory.user_created` organization.directory.user_created ```json 1 { 2 "spec_version": "1", 3 "id": "evt_53891546994442316", 4 "type": "organization.directory.user_created", 5 "occurred_at": "2025-01-06T18:44:25.153954Z", 6 "environment_id": "env_53814739859406915", 7 "organization_id": "org_53879494091473415", 8 "object": "DirectoryUser", 9 "data": { 10 "active": true, 11 "custom_attributes": { 12 "mobile_phone_number": "+1-555-0101" 13 }, 14 "department": "Engineering", 15 "dp_id": "00u1a2b3c4d5e6f7g8h9", 16 "email": "john.doe@acmecorp.com", 17 "employee_id": "E1234", 18 "family_name": "Doe", 19 "given_name": "John", 20 "groups": [ 21 { 22 "id": "dirgroup_53891546960887900", 23 "name": "Engineering" 24 } 25 ], 26 "id": "diruser_53891546960887884", 27 "locale": "en-US", 28 "name": "John Doe", 29 "organization_id": "org_53879494091473415", 30 "phone_number": "+1-555-0100", 31 "preferred_username": "john.doe@acmecorp.com", 32 "raw_attributes": { 33 "active": true, 34 "externalId": "00u1a2b3c4d5e6f7g8h9", 35 "userName": "john.doe@acmecorp.com" 36 }, 37 "roles": [ 38 { 39 "role_name": "billing_admin" 40 } 41 ], 42 "title": "Software Engineer", 43 "zoneinfo": "America/New_York" 44 } 45 } ``` ### `organization.directory.user_updated` organization.directory.user_updated ```json 1 { 2 "spec_version": "1", 3 "id": "evt_53891546994442317", 4 "type": "organization.directory.user_updated", 5 "occurred_at": "2025-01-06T18:44:25.153954Z", 6 "environment_id": "env_53814739859406915", 7 "organization_id": "org_53879494091473415", 8 "object": "DirectoryUser", 9 "data": { 10 "active": true, 11 "custom_attributes": { 12 "mobile_phone_number": "+1-555-0101" 13 }, 14 "department": "Engineering", 15 "dp_id": "00u1a2b3c4d5e6f7g8h9", 16 "email": "john.doe@acmecorp.com", 17 "employee_id": "E1234", 18 "family_name": "Doe", 19 "given_name": "John", 20 "groups": [ 21 { 22 "id": "dirgroup_53891546960887900", 23 "name": "Engineering" 24 } 25 ], 26 "id": "diruser_53891546960887884", 27 "locale": "en-US", 28 "name": "John Doe", 29 "organization_id": "org_53879494091473415", 30 "phone_number": "+1-555-0100", 31 "preferred_username": "john.doe@acmecorp.com", 32 "raw_attributes": { 33 "active": true, 34 "externalId": "00u1a2b3c4d5e6f7g8h9", 35 "userName": "john.doe@acmecorp.com" 36 }, 37 "roles": [ 38 { 39 "role_name": "billing_admin" 40 } 41 ], 42 "title": "Senior Software Engineer", 43 "zoneinfo": "America/New_York" 44 } 45 } ``` ### `organization.directory.user_deleted` This example is a deactivated user, so `active` is `false`. organization.directory.user_deleted ```json 1 { 2 "spec_version": "1", 3 "id": "evt_53891546994442318", 4 "type": "organization.directory.user_deleted", 5 "occurred_at": "2025-01-06T18:44:25.153954Z", 6 "environment_id": "env_53814739859406915", 7 "organization_id": "org_53879494091473415", 8 "object": "DirectoryUser", 9 "data": { 10 "active": false, 11 "custom_attributes": { 12 "mobile_phone_number": "+1-555-0101" 13 }, 14 "department": "Engineering", 15 "dp_id": "00u1a2b3c4d5e6f7g8h9", 16 "email": "john.doe@acmecorp.com", 17 "employee_id": "E1234", 18 "family_name": "Doe", 19 "given_name": "John", 20 "groups": [ 21 { 22 "id": "dirgroup_53891546960887900", 23 "name": "Engineering" 24 } 25 ], 26 "id": "diruser_53891546960887884", 27 "locale": "en-US", 28 "name": "John Doe", 29 "organization_id": "org_53879494091473415", 30 "phone_number": "+1-555-0100", 31 "preferred_username": "john.doe@acmecorp.com", 32 "raw_attributes": { 33 "active": false, 34 "externalId": "00u1a2b3c4d5e6f7g8h9", 35 "userName": "john.doe@acmecorp.com" 36 }, 37 "roles": [ 38 { 39 "role_name": "billing_admin" 40 } 41 ], 42 "title": "Software Engineer", 43 "zoneinfo": "America/New_York" 44 } 45 } ``` ## Directory group events All three group events send the same group object in `data`. Every key is sent, even when its value is `null`. | Field | Type | Description | | ----------------- | -------------- | ----------------------------------------------------------------------------------- | | `id` | string | Directory group ID, prefixed with `dirgroup_` | | `organization_id` | string | Organization the group belongs to | | `directory_id` | string | Directory the group belongs to | | `display_name` | string | Group display name | | `dp_id` | string or null | The group’s `externalId` from the provider. `null` if the provider doesn’t send one | | `raw_attributes` | object or null | The SCIM group resource as received from the provider | ### `organization.directory.group_created` organization.directory.group_created ```json 1 { 2 "spec_version": "1", 3 "id": "evt_38862741515010639", 4 "type": "organization.directory.group_created", 5 "occurred_at": "2024-09-25T02:26:39.036398577Z", 6 "environment_id": "env_32080745237316098", 7 "organization_id": "org_38609339635728478", 8 "object": "DirectoryGroup", 9 "data": { 10 "directory_id": "dir_38610496391217780", 11 "display_name": "Engineering", 12 "dp_id": "00g1a2b3c4d5e6f7g8h9", 13 "id": "dirgroup_38862741498233423", 14 "organization_id": "org_38609339635728478", 15 "raw_attributes": { 16 "displayName": "Engineering", 17 "externalId": "00g1a2b3c4d5e6f7g8h9" 18 } 19 } 20 } ``` ### `organization.directory.group_updated` organization.directory.group_updated ```json 1 { 2 "spec_version": "1", 3 "id": "evt_38864948910162368", 4 "type": "organization.directory.group_updated", 5 "occurred_at": "2024-09-25T02:48:34.745030921Z", 6 "environment_id": "env_32080745237316098", 7 "organization_id": "org_38609339635728478", 8 "object": "DirectoryGroup", 9 "data": { 10 "directory_id": "dir_38610496391217780", 11 "display_name": "Platform Engineering", 12 "dp_id": "00g1a2b3c4d5e6f7g8h9", 13 "id": "dirgroup_38862741498233423", 14 "organization_id": "org_38609339635728478", 15 "raw_attributes": { 16 "displayName": "Platform Engineering", 17 "externalId": "00g1a2b3c4d5e6f7g8h9" 18 } 19 } 20 } ``` ### `organization.directory.group_deleted` organization.directory.group_deleted ```json 1 { 2 "spec_version": "1", 3 "id": "evt_40650399597723966", 4 "type": "organization.directory.group_deleted", 5 "occurred_at": "2024-10-07T10:25:26.289331747Z", 6 "environment_id": "env_12205603854221623", 7 "organization_id": "org_39802449573184223", 8 "object": "DirectoryGroup", 9 "data": { 10 "directory_id": "dir_39802485862301855", 11 "display_name": "Admins", 12 "dp_id": "7c66a173-79c6-4270-ac78-8f35a8121e0a", 13 "id": "dirgroup_40072007005503806", 14 "organization_id": "org_39802449573184223", 15 "raw_attributes": {} 16 } 17 } ``` --- # DOCUMENT BOUNDARY --- # Ways to implement SSO logins > Implement single sign-on on your login page using three UX strategies: identifier-driven, SSO button, or organization-specific pages. Single sign-on (SSO) login requires careful UX design to balance enterprise authentication requirements with user experience. Your login page must accommodate both SSO users (who authenticate through their organization’s identity provider) and non-SSO users (who use passwords or social authentication). This guide presents three proven UX strategies for adding SSO to your login page. Each strategy offers different trade-offs between user experience, implementation complexity, and administrative control. Choose the approach that best fits your users’ needs and your application’s architecture. The right strategy depends on your user base: identifier-driven flows work best when admins control authentication methods, explicit SSO buttons give users choice, and organization-specific login pages simplify enterprise deployments. ![Login page with password and social auth methods](/.netlify/images?url=_astro%2Fsimple_login_page.CjjjVgoK.png\&w=1024\&h=1222\&dpl=6aedac7ec39c4cadbcd1959e) ## Strategy 1: Identifier-driven single sign-on [Section titled “Strategy 1: Identifier-driven single sign-on”](#strategy-1-identifier-driven-single-sign-on) Collect the user’s email address first. Use the email domain or organization identifier to determine whether to route to SSO or password-based authentication. ![Identifier-driven login](/.netlify/images?url=_astro%2Fidentifier_first_login.BlfaJ4QS.png\&w=2222\&h=1044\&dpl=6aedac7ec39c4cadbcd1959e) Users don’t choose the authentication method. This reduces cognitive load and works well when admins mandate SSO after users have already logged in with passwords. Popular products like [Google](https://accounts.google.com), [Microsoft](https://login.microsoftonline.com), and [AWS](https://console.aws.amazon.com/console/) use this strategy. ## Strategy 2: Login with single sign-on button [Section titled “Strategy 2: Login with single sign-on button”](#strategy-2-login-with-single-sign-on-button) Add a “Login with SSO” button to your login page. This presents all authentication options and lets users choose their preferred method. ![Explicit option for login with SSO](/.netlify/images?url=_astro%2Fsso_button_login.onnUOag1.png\&w=1082\&h=1242\&dpl=6aedac7ec39c4cadbcd1959e) If a user attempts password login but their admin mandates SSO, force SSO-based authentication instead of showing an error. Popular products like [Cal.com](https://app.cal.com/auth/login) and [Notion](https://www.notion.so/login) use this strategy. ## Strategy 3: organization-specific login page [Section titled “Strategy 3: organization-specific login page”](#strategy-3-organization-specific-login-page) Serve different login pages for each organization instead of a single login page. For example, `https://customer1.b2b-app.com/login` and `https://customer2.b2b-app.com/login`. Show only the authentication methods applicable to that organization based on the URL. Popular products like [Zendesk](https://www.zendesk.com/in/login/) and [Slack](https://scalekit.slack.com/) use this strategy. The drawback is that users must remember their organization URL to access the login page. *** ## Next steps [Section titled “Next steps”](#next-steps) After implementing your chosen SSO login strategy: * [Pre-check SSO by domain](/guides/user-auth/check-sso-domain/) - Validate email domains have active SSO before redirecting * [Complete login with code exchange](/authenticate/fsa/complete-login/) - Exchange authorization codes for user data and tokens * [Manage user sessions](/authenticate/fsa/manage-session/) - Store and validate session tokens securely --- # DOCUMENT BOUNDARY --- # Authorization URL to initiate SSO > Learn how to construct and implement authorization URLs in Scalekit to initiate secure Single Sign-on (SSO) flows with your identity provider. The authorization endpoint is where your application redirects users to begin the authentication process. Scalekit powers this endpoint and handles redirecting users to the appropriate identity provider. Example authorization URL ```sh https://SCALEKIT_ENVIRONMENT_URL/oauth/authorize? response_type=code& client_id=skc_1234& scope=openid%20profile& redirect_uri=https%3A%2F%2Fyoursaas.com%2Fcallback& organization_id=org_1243412& state=aHR0cHM6Ly95b3Vyc2Fhcy5jb20vZGVlcGxpbms%3D ``` ## Parameters [Section titled “Parameters”](#parameters) | Parameter | Requirement | Description | | ----------------- | ----------- | -------------------------------------------------------------------------------------------------------------------------------- | | `client_id` | Required | Your unique client identifier from the API credentials page | | `nonce` | Optional | Random value for replay protection | | `organization_id` | Required\* | Identifier for the organization initiating SSO | | `connection_id` | Required\* | Identifier for the specific SSO connection | | `domain` | Required\* | Domain portion of email addresses configured for an organization | | `provider` | Required\* | Social login provider name. Supported providers: `google`, `microsoft`, `github`, `gitlab`, `linkedin`, `salesforce`, `facebook` | | `response_type` | Required | Must be set to `code` | | `redirect_uri` | Required | URL where Scalekit sends the response. Must match an authorized redirect URI | | `scope` | Required | Must be set to `openid email profile` | | `state` | Optional | Opaque string for request-response correlation | | `login_hint` | Optional | User’s email address for prefilling the login form | \* You must provide one of `organization_id`, `connection_id`, `domain`, or `provider`. If you identify SSO connection using `domain` or `login_hint`, the domain must be registered to the organization. Register domains in **Dashboard > Organizations > General**, or let customers add them via the admin portal. See [Onboard enterprise customers](/sso/guides/onboard-enterprise-customers/). ## SDK usage [Section titled “SDK usage”](#sdk-usage) Use Scalekit SDKs to generate authorization URLs programmatically. This approach handles parameter encoding and validation automatically. * Node.js ```javascript 1 import { ScalekitClient } from '@scalekit-sdk/node'; 2 3 const scalekit = new ScalekitClient( 4 'https://your-subdomain.scalekit.dev', 5 '', 6 '' 7 ); 8 9 const options = { 10 loginHint: 'user@example.com', 11 organizationId: 'org_123235245', 12 }; 13 14 const authorizationURL = scalekit.getAuthorizationUrl(redirectUri, options); 15 // Example generated URL: 16 // https://your-subdomain.scalekit.dev/oauth/authorize?response_type=code&client_id=skc_1234&scope=openid%20profile&redirect_uri=https%3A%2F%2Fyoursaas.com%2Fcallback&organization_id=org_123235245&login_hint=user%40example.com&state=abc123 ``` * Python ```python 1 from scalekit import ScalekitClient, AuthorizationUrlOptions 2 3 scalekit = ScalekitClient( 4 'https://your-subdomain.scalekit.dev', 5 '', 6 '' 7 ) 8 9 options = AuthorizationUrlOptions() 10 options.organization_id = "org_12345" 11 options.login_hint = "user@example.com" 12 13 authorization_url = scalekit.get_authorization_url( 14 redirect_uri, 15 options 16 ) 17 # Example generated URL: 18 # https://your-subdomain.scalekit.dev/oauth/authorize?response_type=code&client_id=skc_1234&scope=openid%20profile&redirect_uri=https%3A%2F%2Fyoursaas.com%2Fcallback&organization_id=org_12345&login_hint=user%40example.com&state=abc123 ``` * Go ```go 1 package main 2 3 import ( 4 "fmt" 5 "log" 6 7 scalekit "github.com/scalekit-inc/scalekit-sdk-go/v2" 8 ) 9 10 func main() { 11 scalekitClient := scalekit.NewScalekitClient( 12 "https://your-subdomain.scalekit.dev", 13 "", 14 "", 15 ) 16 redirectUrl := "https://yoursaas.com/callback" 17 18 options := scalekit.AuthorizationUrlOptions{ 19 OrganizationId: "org_12345", 20 LoginHint: "user@example.com", 21 } 22 23 authorizationURL, err := scalekitClient.GetAuthorizationUrl( 24 redirectUrl, 25 options, 26 ) 27 if err != nil { 28 log.Fatal(err) 29 } 30 fmt.Println(authorizationURL.String()) 31 // Example generated URL: 32 // https://your-subdomain.scalekit.dev/oauth/authorize?response_type=code&client_id=skc_1234&scope=openid%20profile&redirect_uri=https%3A%2F%2Fyoursaas.com%2Fcallback&organization_id=org_12345&login_hint=user%40example.com&state=abc123 33 } ``` * Java ```java 1 package com.scalekit; 2 3 import com.scalekit.ScalekitClient; 4 import com.scalekit.internal.http.AuthorizationUrlOptions; 5 6 public class Main { 7 public static void main(String[] args) { 8 ScalekitClient scalekitClient = new ScalekitClient( 9 "https://your-subdomain.scalekit.dev", 10 "", 11 "" 12 ); 13 AuthorizationUrlOptions options = new AuthorizationUrlOptions(); 14 // Option 1: Authorization URL with the organization ID 15 options.setOrganizationId("org_13388706786312310"); 16 // Option 2: Authorization URL with the connection ID 17 options.setConnectionId("con_13388706786312310"); 18 // Option 3: Authorization URL with login hint 19 options.setLoginHint("user@example.com"); 20 String redirectUrl = "https://yoursaas.com/callback"; 21 22 try { 23 String url = scalekitClient.authentication().getAuthorizationUrl(redirectUrl, options).toString(); 24 // Example generated URL: 25 // https://your-subdomain.scalekit.dev/oauth/authorize?response_type=code&client_id=skc_1234&scope=openid%20profile&redirect_uri=https%3A%2F%2Fyoursaas.com%2Fcallback&organization_id=org_13388706786312310&connection_id=con_13388706786312310&login_hint=user%40example.com&state=abc123 26 } catch (Exception e) { 27 System.out.println(e.getMessage()); 28 } 29 } 30 } ``` ## Parameter precedence [Section titled “Parameter precedence”](#parameter-precedence) When you provide multiple connection parameters, Scalekit follows a specific precedence order to determine which identity provider to use: 1. `provider` (highest precedence): If present, Scalekit ignores all other connection parameters and directs users to the specified social login provider. For example, `provider=google` redirects users to Google’s login screen. See [Social Login](/authenticate/auth-methods/social-logins/) for more details. 2. `connection_id`: Takes highest precedence among enterprise SSO parameters. Scalekit uses this specific connection if you provide a valid connection ID. If the connection ID is invalid, the authorization request fails. 3. `organization_id`: Scalekit uses this parameter when no valid `connection_id` is provided. It selects the SSO connection configured for the specified organization. 4. `domain`: Scalekit uses this parameter when neither `connection_id` nor `organization_id` are provided. It selects the SSO connection configured for the specified domain. 5. `login_hint` (lowest precedence): Scalekit extracts the domain portion from the email address and uses the corresponding SSO connection mapped to that organization. The domain must be registered to the organization either manually from the Scalekit Dashboard or through the admin portal when [onboarding an enterprise customer](/sso/guides/onboard-enterprise-customers/). ## Common scenarios [Section titled “Common scenarios”](#common-scenarios) --- # DOCUMENT BOUNDARY --- # Handle identity provider initiated SSO > Learn how to securely implement IdP-initiated Single Sign-On for your application This guide shows you how to securely implement Identity Provider (IdP)-initiated Single Sign-On for your application. When users log into your application directly from their identity provider’s portal, Scalekit converts the IdP-initiated request to a Service Provider (SP)-initiated flow for enhanced security. The workflow converts the traditional IdP-initiated flow to a secure SP-initiated flow by: 1. The user logs into their identity provider portal and selects your application 2. The identity provider sends user details as assertions to Scalekit 3. Scalekit redirects to your initiate login endpoint with a JWT token 4. Your application validates the JWT and generates a new SP-initiated authorization URL To securely implement IdP-initiated SSO, follow these steps to convert incoming IdP-initiated requests to SP-initiated flows: 1. Set up an initiate login endpoint and register it in **Dashboard > Developers > Redirect URLs > Initiate Login URL** 2. Extract information from the JWT token containing organization, connection, and user details 3. Convert to SP-initiated flow using the extracted parameters to generate a new authorization URL 4. Handle errors with proper callback processing and error handling best practices ## Implementation examples [Section titled “Implementation examples”](#implementation-examples) Use the extracted parameters to initiate a new SSO request. This converts the IdP-initiated flow to a secure SP-initiated flow. Here are implementation examples: * Node.js Express.js ```javascript 1 // Security: ALWAYS verify requests are from Scalekit before processing 2 // This prevents unauthorized parties from triggering your interceptor logic 3 4 // Use case: Handle IdP-initiated SSO requests from enterprise customer portals 5 // Examples: Okta dashboard, Azure AD portal, Google Workspace apps 6 7 const crypto = require('node:crypto'); 8 const express = require('express'); 9 const app = express(); 10 // Uses express-session, as in https://docs.scalekit.com/authenticate/sso/handle-callback/ 11 12 app.get('/login', async (req, res) => { 13 try { 14 // Your Initiate Login Endpoint receives a JWT 15 const { error_description, idp_initiated_login } = req.query; 16 17 if (error_description) { 18 return res.redirect('/sign-in?error=auth_failed'); 19 } 20 21 // Decode the JWT and extract claims 22 if (idp_initiated_login) { 23 const { 24 connection_id, 25 organization_id, 26 login_hint, 27 relay_state 28 } = await scalekit.getIdpInitiatedLoginClaims(idp_initiated_login); 29 30 // Use ONE of the following properties for authorization 31 const options = {}; 32 if (connection_id) options.connectionId = connection_id; 33 if (organization_id) options.organizationId = organization_id; 34 if (login_hint) options.loginHint = login_hint; 35 36 // Store a state value for your callback to check, as for any login 37 options.state = crypto.randomBytes(16).toString('hex'); 38 req.session.ssoState = options.state; 39 // relay_state is where the user should land after login, if the IdP sent one 40 if (relay_state) req.session.relayState = relay_state; 41 42 // Generate Authorization URL for SP-initiated flow 43 const url = scalekit.getAuthorizationUrl( 44 process.env.REDIRECT_URI, 45 options 46 ); 47 48 return res.redirect(url); 49 } 50 51 // No token: a regular visit. Send it to your app's sign-in page, which must be a 52 // different route from this endpoint, or the browser redirects in a loop. 53 res.redirect('/sign-in'); 54 } catch (error) { 55 console.error('IdP-initiated login error:', error); 56 res.redirect('/sign-in?error=auth_failed'); 57 } 58 }); ``` * Python Flask ```python 1 # Security: ALWAYS verify requests are from Scalekit before processing 2 # This prevents unauthorized parties from triggering your interceptor logic 3 4 # Use case: Handle IdP-initiated SSO requests from enterprise customer portals 5 # Examples: Okta dashboard, Azure AD portal, Google Workspace apps 6 7 from flask import Flask, request, redirect, session 8 import os 9 import secrets 10 11 app = Flask(__name__) 12 13 @app.route('/login') 14 def login(): 15 try: 16 # Your Initiate Login Endpoint receives a JWT 17 error_description = request.args.get('error_description') 18 idp_initiated_login = request.args.get('idp_initiated_login') 19 20 if error_description: 21 return redirect('/sign-in?error=auth_failed') 22 23 # Decode the JWT and extract claims 24 if idp_initiated_login: 25 claims = scalekit_client.get_idp_initiated_login_claims(idp_initiated_login) 26 27 # Extract claims with fallbacks 28 connection_id = claims.get('connection_id') 29 organization_id = claims.get('organization_id') 30 login_hint = claims.get('login_hint') 31 relay_state = claims.get('relay_state') 32 33 # Create authorization options 34 options = AuthorizationUrlOptions() 35 if connection_id: 36 options.connection_id = connection_id 37 if organization_id: 38 options.organization_id = organization_id 39 if login_hint: 40 options.login_hint = login_hint 41 42 # Store a state value for your callback to check, as for any login 43 options.state = secrets.token_urlsafe(16) 44 session['sso_state'] = options.state 45 # relay_state is where the user should land after login, if the IdP sent one 46 if relay_state: 47 session['relay_state'] = relay_state 48 49 # Generate Authorization URL for SP-initiated flow 50 authorization_url = scalekit_client.get_authorization_url( 51 redirect_uri=os.getenv('REDIRECT_URI'), 52 options=options 53 ) 54 55 return redirect(authorization_url) 56 57 # No token: a regular visit. Send it to your app's sign-in page, which must be a 58 # different route from this endpoint, or the browser redirects in a loop. 59 return redirect('/sign-in') 60 except Exception as error: 61 print(f"IdP-initiated login error: {error}") 62 return redirect('/sign-in?error=auth_failed') ``` * Go Gin ```go 1 // Security: ALWAYS verify requests are from Scalekit before processing 2 // This prevents unauthorized parties from triggering your interceptor logic 3 4 // Use case: Handle IdP-initiated SSO requests from enterprise customer portals 5 // Examples: Okta dashboard, Azure AD portal, Google Workspace apps 6 7 package main 8 9 import ( 10 "net/http" 11 "github.com/gin-gonic/gin" 12 ) 13 14 func (a *App) handleLogin(c *gin.Context) { 15 // Your Initiate Login Endpoint receives a JWT 16 errDescription := c.Query("error_description") 17 idpInitiatedLogin := c.Query("idp_initiated_login") 18 19 if errDescription != "" { 20 c.Redirect(http.StatusFound, "/sign-in?error=auth_failed") 21 return 22 } 23 24 // Decode the JWT and extract claims 25 if idpInitiatedLogin != "" { 26 claims, err := scalekitClient.GetIdpInitiatedLoginClaims(c.Request.Context(), idpInitiatedLogin) 27 if err != nil { 28 http.Error(c.Writer, err.Error(), http.StatusInternalServerError) 29 return 30 } 31 32 // Create authorization options with ONE of the following properties 33 options := scalekit.AuthorizationUrlOptions{} 34 if claims.ConnectionID != "" { 35 options.ConnectionId = claims.ConnectionID 36 } 37 if claims.OrganizationID != "" { 38 options.OrganizationId = claims.OrganizationID 39 } 40 if claims.LoginHint != "" { 41 options.LoginHint = claims.LoginHint 42 } 43 44 // Store a state value for your callback to check, as for any login 45 options.State = randomHex() // as in https://docs.scalekit.com/authenticate/sso/handle-callback/ 46 http.SetCookie(c.Writer, &http.Cookie{ 47 Name: "sso_state", Value: options.State, Path: "/auth", MaxAge: 600, 48 HttpOnly: true, Secure: true, SameSite: http.SameSiteLaxMode, 49 }) 50 // claims.RelayState, if set, is where the user should land after login 51 52 // Generate Authorization URL for SP-initiated flow 53 authUrl, err := scalekitClient.GetAuthorizationUrl(redirectUrl, options) 54 if err != nil { 55 http.Error(c.Writer, err.Error(), http.StatusInternalServerError) 56 return 57 } 58 59 c.Redirect(http.StatusFound, authUrl.String()) 60 return 61 } 62 63 // No token: a regular visit. Send it to your app's sign-in page, which must be a 64 // different route from this endpoint, or the browser redirects in a loop. 65 c.Redirect(http.StatusFound, "/sign-in") 66 } ``` * Java Spring Boot ```java 1 // Security: ALWAYS verify requests are from Scalekit before processing 2 // This prevents unauthorized parties from triggering your interceptor logic 3 4 // Use case: Handle IdP-initiated SSO requests from enterprise customer portals 5 // Examples: Okta dashboard, Azure AD portal, Google Workspace apps 6 7 import com.scalekit.ScalekitClient; 8 import com.scalekit.internal.http.AuthorizationUrlOptions; 9 import com.scalekit.internal.http.IdpInitiatedLoginClaims; 10 import org.springframework.http.HttpStatus; 11 import org.springframework.web.bind.annotation.*; 12 import org.springframework.web.servlet.view.RedirectView; 13 import jakarta.servlet.http.HttpServletResponse; 14 import jakarta.servlet.http.HttpSession; 15 import java.io.IOException; 16 import java.security.SecureRandom; 17 import java.util.HexFormat; 18 19 @RestController 20 public class AuthController { 21 22 @GetMapping("/login") 23 public RedirectView handleLogin( 24 @RequestParam(required = false, name = "error_description") String errorDescription, 25 @RequestParam(required = false, name = "idp_initiated_login") String idpInitiatedLoginToken, 26 HttpSession session, 27 HttpServletResponse response) throws IOException { 28 29 if (errorDescription != null) { 30 return new RedirectView("/sign-in?error=auth_failed"); 31 } 32 33 // Decode the JWT and extract claims 34 if (idpInitiatedLoginToken != null) { 35 IdpInitiatedLoginClaims claims = scalekitClient.authentication() 36 .getIdpInitiatedLoginClaims(idpInitiatedLoginToken); 37 38 if (claims == null) { 39 response.sendError(HttpStatus.BAD_REQUEST.value(), 40 "Invalid idp_initiated_login token"); 41 return null; 42 } 43 44 // Create authorization options with ONE of the following 45 AuthorizationUrlOptions options = new AuthorizationUrlOptions(); 46 if (claims.getConnectionID() != null) { 47 options.setConnectionId(claims.getConnectionID()); 48 } 49 if (claims.getOrganizationID() != null) { 50 options.setOrganizationId(claims.getOrganizationID()); 51 } 52 if (claims.getLoginHint() != null) { 53 options.setLoginHint(claims.getLoginHint()); 54 } 55 56 // Store a state value for your callback to check, as for any login 57 byte[] bytes = new byte[16]; 58 new SecureRandom().nextBytes(bytes); 59 String state = HexFormat.of().formatHex(bytes); 60 session.setAttribute("ssoState", state); 61 options.setState(state); 62 // relayState is where the user should land after login, if the IdP sent one 63 if (claims.getRelayState() != null) { 64 session.setAttribute("relayState", claims.getRelayState()); 65 } 66 67 // Generate Authorization URL for SP-initiated flow 68 String url = scalekitClient.authentication() 69 .getAuthorizationUrl(redirectUrl, options) 70 .toString(); 71 72 response.sendRedirect(url); 73 return null; 74 } 75 76 // No token: a regular visit. Send it to your app's sign-in page, which must be a 77 // different route from this endpoint, or the browser redirects in a loop. 78 return new RedirectView("/sign-in"); 79 } 80 } ``` ## Implementation details [Section titled “Implementation details”](#implementation-details) ### Endpoint setup [Section titled “Endpoint setup”](#endpoint-setup) Implement this as a backend route, not a frontend page. Scalekit redirects the browser to the Initiate Login URL with a `GET` request; your server reads the `idp_initiated_login` parameter, validates it, and issues its own redirect to continue the flow — the route never renders a page. Your initiate login endpoint will receive requests with the following format: ```sh https://yourapp.com/login?idp_initiated_login= ``` ### JWT token structure [Section titled “JWT token structure”](#jwt-token-structure) The `idp_initiated_login` parameter contains a signed JWT with organization, connection, and user details. ### Error callback format [Section titled “Error callback format”](#error-callback-format) If errors occur, the redirect URI will receive a callback with this format: ```sh https://{your-subdomain}.scalekit.dev/callback ?error="" &error_description="
" ``` After completing the SP-initiated flow, users are redirected back to your callback URL where you can complete the authentication process. Next, let’s look at how to test your IdP-initiated SSO implementation. ## Integrating with a downstream auth provider [Section titled “Integrating with a downstream auth provider”](#integrating-with-a-downstream-auth-provider) If your application uses a third-party service like [Firebase Authentication](/guides/integrations/auth-systems/firebase/) to manage user sessions, you must initiate its sign-in flow after completing **Step 3**. This process has two stages: first, the IdP redirects the user to your app via Scalekit, and second, your app triggers a new sign-in flow with Firebase using the Authorization URL you just generated. The example below shows how to pass the Authorization URL to the Firebase Web SDK. * Firebase (Web SDK) Firebase Web SDK ```javascript import { getAuth, OAuthProvider, signInWithRedirect } from "firebase/auth"; // Security: Configure OIDC provider properly to prevent token injection const auth = getAuth(); // "scalekit" is the OIDC provider you configured in Firebase const scalekitProvider = new OAuthProvider("scalekit"); // Use the authorizationUrl generated in Step 3 scalekitProvider.setCustomParameters({ connection_id: "", // Enables Firebase to forward the connection ID to Scalekit }); // Initiate Firebase sign-in with Scalekit provider signInWithRedirect(auth, scalekitProvider); ``` ## Security considerations [Section titled “Security considerations”](#security-considerations) While IdP-initiated SSO offers convenience, it comes with significant security risks. Scalekit’s approach converts the flow to SP-initiated to mitigate these vulnerabilities. ### Traditional IdP-initiated SSO security risks [Section titled “Traditional IdP-initiated SSO security risks”](#traditional-idp-initiated-sso-security-risks) **Stolen SAML assertions**: Attackers can steal SAML assertions and use them to gain unauthorized access. If an attacker manages to steal these assertions, they can: * Inject them into another service provider, gaining access to that user’s account * Inject them back into your application with altered assertions, potentially elevating their privileges With a stolen SAML assertion, an attacker can gain access to your application as the compromised user, bypassing the usual authentication process. ### How attackers steal SAML assertions [Section titled “How attackers steal SAML assertions”](#how-attackers-steal-saml-assertions) Attackers can steal SAML assertions through various methods: * **Man-in-the-middle (MITM) attacks**: Intercepting and replacing the SAML response during transmission * **Open redirect attacks**: Exploiting improper endpoint validation to redirect the SAML response to a malicious server * **Leaky logs and headers**: Sensitive information, including SAML assertions, can be leaked through logs or headers * **Browser-based attacks**: Exploiting browser vulnerabilities to steal SAML assertions ### The challenge for service providers [Section titled “The challenge for service providers”](#the-challenge-for-service-providers) The chief problem with stolen assertions is that everything appears legitimate to the service provider (your application). The message and assertion are valid, issued by the expected identity provider, and signed with the expected key. However, the service provider cannot verify whether the assertions are stolen or not. If you encounter issues implementing IdP-initiated SSO: 1. **Verify configuration**: Ensure your redirect URI is properly configured in **Dashboard > Developers > Redirect URLs** 2. **Check JWT processing**: Verify you’re correctly processing the JWT token from the `idp_initiated_login` parameter 3. **Validate error handling**: Ensure your error handling properly captures and processes any error messages 4. **Test connections**: Confirm the organization and connection IDs in the JWT are valid and active 5. **Review logs**: Check both your application logs and Scalekit dashboard logs for debugging information Common issues The most frequent issue is mismatched redirect URLs between your code and the Scalekit dashboard configuration. Ensure URLs match exactly, including protocol (http/https) and trailing slashes. --- # DOCUMENT BOUNDARY --- # Production readiness checklist > A focused checklist for launching your Scalekit SSO integration, based on the core enterprise authentication launch checks. As you prepare to launch enterprise SSO to production, you should confirm that your configuration satisfies the core enterprise checks from the authentication launch checklist. This page extracts the SSO-specific items from the main authentication [production readiness checklist](/authenticate/launch-checklist/) and organizes them for your SSO rollout. Use this checklist alongside the main launch checklist to validate that your SSO flows, admin experience, and network access are ready for enterprise customers. **Verify production environment configuration** Confirm that your environment URL (`SCALEKIT_ENVIRONMENT_URL`), client ID (`SCALEKIT_CLIENT_ID`), and client secret (`SCALEKIT_CLIENT_SECRET`) are correctly configured for your production environment and match your production Scalekit dashboard settings. **Verify SSO integrations with identity providers** Test SSO integrations with your target identity providers (for example, Okta, Azure AD, Google Workspace) using your production environment URL and credentials. **Configure SSO attribute mapping and identifiers** Configure SSO user attribute mapping (email, name, groups) and ensure you use consistent user identifiers (for example, email or `userPrincipalName`) across all SSO connections. **Verify redirect URIs and state validation** Confirm that your redirect URIs are correctly configured in both Scalekit and your identity providers, and that you validate the `state` parameter in callbacks to prevent CSRF attacks. **Test SP-initiated and IdP-initiated SSO flows** Test both SP-initiated and IdP-initiated SSO flows end-to-end in a staging environment before enabling them for production tenants. See [test SSO flows](/sso/guides/test-sso) for detailed scenarios. **Finalize admin portal setup and branding** Configure the self-service admin portal, apply your branding (logo, accent colors), and verify that enterprise admins can manage SSO connections and users as expected. **Review admin portal URL and DNS** Customize the admin portal URL to match your domain (for example, `https://sso.b2b-app.com`), update your `.env` configuration after CNAME setup, and confirm that your customers can access the portal from their networks. **Verify customer network and firewall access** Ask your enterprise customers to whitelist your Scalekit environment domain and related endpoints so SSO redirects and admin portal access work behind their VPNs and firewalls. **Harden error handling and monitoring for SSO** Test SSO error scenarios (for example, misconfigured connections, invalid assertions, and deactivated users), and set up logging and alerts so you can quickly detect and remediate SSO issues. --- # DOCUMENT BOUNDARY --- # Onboard enterprise customers > Complete workflow for enabling enterprise SSO and self-serve configuration for your customers Enterprise SSO enables users to authenticate to your application using their organization’s identity provider (IdP) such as Okta, Microsoft Entra ID, or Google Workspace. This provides enterprise customers with a secure, centralized authentication experience while reducing password management overhead. ![How Scalekit connects your application to enterprise identity providers](/.netlify/images?url=_astro%2Fhow-scalekit-connects.CrZX8E30.png\&w=5776\&h=1924\&dpl=6aedac7ec39c4cadbcd1959e) This guide walks you through the complete workflow for onboarding enterprise customers with SSO. You’ll learn how to create organizations, provide admin portal access, enable domain-based SSO, and verify the integration. Before onboarding enterprise customers, ensure you have completed the [Full Stack Auth quickstart](/authenticate/fsa/quickstart/) to set up basic authentication in your application. ## Table of contents * [Create organization](#create-organization) * [Provide admin portal access](#provide-admin-portal-access) * [Customer configures SSO](#customer-configures-sso) * [Verify domain ownership](#verify-domain-ownership) 1. ## Create organization Create an organization in Scalekit to represent your enterprise customer: * Log in to the [Scalekit dashboard](https://app.scalekit.com) * Navigate to **Dashboard > Organizations** * Click **Create Organization** * Enter the organization name and relevant details * Save the organization Each organization in Scalekit represents one of your enterprise customers and can have its own SSO configuration, directory sync settings, and domain associations. 2. ## Provide admin portal access Give your customer’s IT administrator access to the self-serve admin portal to configure their identity provider. Scalekit provides two integration methods: **Option 1: Share a no-code link** Quick setup Generate and share a link to the admin portal: * Select the organization from **Dashboard > Organizations** * Click **Generate link** in the organization overview * Share the link with your customer’s IT admin via email, Slack, or your preferred channel The link remains valid for 7 days and can be revoked anytime from the dashboard. **Link properties:** | Property | Details | | -------------- | ------------------------------------------------------------------------------- | | **Expiration** | Links expire after 7 days | | **Revocation** | Revoke links anytime from the dashboard | | **Sharing** | Share via email, Slack, or any preferred channel | | **Security** | Anyone with the link can view and update the organization’s connection settings | The generated link follows this format: Portal link example ```http https://your-app.scalekit.dev/magicLink/2cbe56de-eec4-41d2-abed-90a5b82286c4_p ``` Security consideration Treat portal links as sensitive credentials. Anyone with the link can view and modify the organization’s SSO and SCIM configuration. **Option 2: Embed the portal** Seamless experience Embed the admin portal directly in your application so customers can configure SSO without leaving your interface. The portal link must be generated programmatically on each page load for security. Each generated link is single-use and expires after 1 minute, though once loaded, the session remains active for up to 6 hours. * Node.js ```bash npm install @scalekit-sdk/node ``` * Python ```sh pip install scalekit-sdk-python ``` * Go ```sh go get -u github.com/scalekit-inc/scalekit-sdk-go/v2 ``` * Java The Java SDK is published to Scalekit’s Maven repository, `https://us-maven.pkg.dev/scalekit-public/java`. Add it to your build next to Maven Central. It needs no credentials. If your builds download dependencies only through a mirror such as Nexus or Artifactory, add this URL to the mirror instead. For Maven, add the `` and `` entries to the matching sections of your existing `pom.xml`. ```groovy // Gradle: build.gradle repositories { mavenCentral() maven { url "https://us-maven.pkg.dev/scalekit-public/java" } } dependencies { implementation "com.scalekit:scalekit-sdk-java:2.6.1" } ``` ```xml scalekit https://us-maven.pkg.dev/scalekit-public/java com.scalekit scalekit-sdk-java 2.6.1 ``` ### Generate portal link Use the Scalekit SDK to generate a unique, embeddable admin portal link for an organization. Call this API endpoint each time you render the page containing the iframe: * Node.js Express.js ```javascript import { Scalekit } from '@scalekit-sdk/node'; const scalekit = new Scalekit( process.env.SCALEKIT_ENVIRONMENT_URL, process.env.SCALEKIT_CLIENT_ID, process.env.SCALEKIT_CLIENT_SECRET, ); async function generatePortalLink(organizationId) { const link = await scalekit.organization.generatePortalLink(organizationId); return link.location; // Use as iframe src } ``` * Python Flask ```python from scalekit import ScalekitClient import os scalekit_client = ScalekitClient( env_url=os.environ.get("SCALEKIT_ENVIRONMENT_URL"), client_id=os.environ.get("SCALEKIT_CLIENT_ID"), client_secret=os.environ.get("SCALEKIT_CLIENT_SECRET") ) def generate_portal_link(organization_id): link = scalekit_client.organization.generate_portal_link(organization_id) return link.location # Use as iframe src ``` * Go Gin ```go 1 import ( 2 "context" 3 "os" 4 5 scalekit "github.com/scalekit-inc/scalekit-sdk-go/v2" 6 ) 7 8 var scalekitClient = scalekit.NewScalekitClient( 9 os.Getenv("SCALEKIT_ENVIRONMENT_URL"), 10 os.Getenv("SCALEKIT_CLIENT_ID"), 11 os.Getenv("SCALEKIT_CLIENT_SECRET"), 12 ) 13 14 func generatePortalLink(organizationID string) (string, error) { 15 ctx := context.Background() 16 link, err := scalekitClient.Organization().GeneratePortalLink(ctx, organizationID) 17 if err != nil { 18 return "", err 19 } 20 return link.Location, nil // Use as iframe src 21 } ``` * Java Spring Boot ```java 1 import com.scalekit.ScalekitClient; 2 import com.scalekit.grpc.scalekit.v1.organizations.Link; 3 import com.scalekit.grpc.scalekit.v1.organizations.Feature; 4 import java.util.Arrays; 5 6 ScalekitClient scalekitClient = new ScalekitClient( 7 System.getenv("SCALEKIT_ENVIRONMENT_URL"), 8 System.getenv("SCALEKIT_CLIENT_ID"), 9 System.getenv("SCALEKIT_CLIENT_SECRET") 10 ); 11 12 public String generatePortalLink(String organizationId) { 13 Link portalLink = scalekitClient.organizations() 14 .generatePortalLink(organizationId, Arrays.asList(Feature.sso, Feature.dir_sync)); 15 return portalLink.getLocation(); // Use as iframe src 16 } ``` The API returns a JSON object with the portal link. Use the `location` property as the iframe `src`: API response ```json { "id": "8930509d-68cf-4e2c-8c6d-94d2b5e2db43", "location": "https://random-subdomain.scalekit.dev/magicLink/8930509d-68cf-4e2c-8c6d-94d2b5e2db43", "expireTime": "2024-10-03T13:35:50.563013Z" } ``` Embed portal in iframe ```html ``` Embed the portal in your application’s settings or admin section where customers manage authentication configuration. Listen for UI events from the embedded portal to respond to configuration changes, such as when SSO is enabled or the session expires. See the [Admin portal UI events reference](/authenticate/sso/admin-portal-events/) for details on handling these events. ### Configuration and session | Setting | Requirement | | --------------------- | ----------------------------------------------------------------------------- | | **Redirect URI** | Add your application domain at **Dashboard > Developers > API Configuration** | | **iframe attributes** | Include `allow="clipboard-write"` for copy-paste functionality | | **Dimensions** | Minimum recommended height: 600px | | **Link expiration** | Generated links expire after 1 minute if not loaded | | **Session duration** | Portal session remains active for up to 6 hours once loaded | | **Single-use** | Each generated link can only be used once to initialize a session | 3. ## Customer configures SSO After receiving admin portal access, your customer’s IT administrator: * Opens the admin portal (via shared link or embedded iframe) * Selects their identity provider (Okta, Microsoft Entra ID, Google Workspace, etc.) * Follows the provider-specific setup guide * Enters the required configuration (metadata URL, certificates, etc.) * Tests the connection * Activates the SSO connection Once configured, the SSO connection appears as active in your organization’s settings: ![Active enterprise SSO connection](/.netlify/images?url=_astro%2Fenterpise-sso-1.BfV9F7Wk.png\&w=2074\&h=1116\&dpl=6aedac7ec39c4cadbcd1959e) 4. ## Verify domain ownership After SSO is configured, verify the organization’s email domains to enable automatic SSO routing. When domains are verified, users with matching email addresses are automatically redirected to their organization’s SSO login. This is also called as **Home Realm Discovery**. ### Manual verification (no DNS required) Domains added via the Scalekit Dashboard or API are marked as **Admin-verified** — no DNS challenge is required. Use this when you have already confirmed domain ownership through another process (contract, business verification, etc.) and want to activate SSO routing immediately. **Via Scalekit Dashboard:** * Navigate to **Dashboard > Organizations** and select the organization * Go to **Overview > Organization Domains** * Click **Add domain** and enter the domain name (e.g., `megacorp.com`) ![Organization domain verification in dashboard](/.netlify/images?url=_astro%2Forg_domain.CnZ3T4x-.png\&w=2940\&h=1588\&dpl=6aedac7ec39c4cadbcd1959e) **Via API:** * cURL ```sh curl 'https:///api/v1/organizations//domains' \ --request POST \ --header 'Authorization: Bearer ' \ --header 'Content-Type: application/json' \ --data '{ "domain": "megacorp.com", "domain_type": "ORGANIZATION_DOMAIN" }' ``` * Node.js ```ts const domain = await scalekit.domain.createDomain(organizationId, 'megacorp.com', { domainType: 'ORGANIZATION_DOMAIN', }); ``` * Python ```python response, _ = scalekit_client.domain.create_domain( organization_id, "megacorp.com", domain_type="ORGANIZATION_DOMAIN", ) domain = response.domain ``` * Go ```go response, err := scalekitClient.Domain().CreateDomain( ctx, organizationID, "megacorp.com", &scalekit.CreateDomainOptions{ DomainType: scalekit.DomainTypeOrganization, }, ) ``` * Java ```java Domain domain = scalekitClient.domains() .createDomain(organizationId, "megacorp.com", DomainType.ORGANIZATION_DOMAIN); ``` ### DNS verification (self-serve for org admins) DNS verification lets your customer’s IT admin prove domain ownership by publishing a TXT record — without involving your team. Scalekit displays the TXT record to publish, then polls DNS automatically until verified. 1. Enable the `Domain Verification` feature for the organization (Dashboard org **Overview** → toggle **Domain Verification**, or via the [API](/apis/#tag/organizations/PATCH/api/v1/organizations/%7Bid%7D/settings)). 2. Generate an Admin Portal link and share it with the org admin. 3. The admin enters the domain in the portal, copies the displayed TXT record, and adds it to their DNS provider (e.g., Cloudflare, Route 53, GoDaddy). 4. Scalekit detects the TXT record automatically and marks the domain as **Verified**. ![Domain verification via admin portal](/.netlify/images?url=_astro%2F2026-05-26-19-01-37.C8CAmZIi.png\&w=2196\&h=1596\&dpl=6aedac7ec39c4cadbcd1959e) Once verified, users with email addresses from that domain (e.g., `user@megacorp.com`) can authenticate using their organization’s SSO. ## Customize the admin portal Match the admin portal to your brand identity. Configure branding at **Dashboard > Settings > Branding**: | Option | Description | | ---------------- | --------------------------------------------------------- | | **Logo** | Upload your company logo (displayed in the portal header) | | **Accent color** | Set the primary color to match your brand palette | | **Favicon** | Provide a custom favicon for browser tabs | For additional customization options including custom domains, see the [Custom domain guide](/authenticate/sso/custom-domain/). ## 5. Test the integration [Section titled “5. Test the integration”](#5-test-the-integration) Before rolling out SSO to your customers, thoroughly test the integration: * **Use the IdP Simulator** during development to test without configuring real identity providers * **Test with real providers** like Okta or Microsoft Entra ID in your staging environment * **Validate all scenarios**: SP-initiated SSO, IdP-initiated SSO, and error handling For complete testing instructions, see the [Test SSO integration guide](/sso/guides/test-sso/). --- # DOCUMENT BOUNDARY --- # Security and compliance for SSO and SCIM > How Scalekit validates SAML responses, enforces PKCE, isolates organizations, handles certificate rotation and gives you its SOC 2 report. Use this page when your security team reviews Scalekit’s modular SSO and SCIM, or when you fill in a vendor security questionnaire. It covers how Scalekit validates sign-in responses from your customers’ identity providers (IdPs), how it protects the authorization code it returns to your app, how it keeps organizations apart, where it stores identity data, and how to get its compliance reports. ## SAML response validation [Section titled “SAML response validation”](#saml-response-validation) Scalekit validates every SAML response before it reads any user attributes from it. Your app receives a user’s profile only after every check below passes. | Check | What Scalekit requires | | ------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | | Signature | The response or the assertion is signed with a certificate configured on the connection. An unsigned response with an unsigned assertion is rejected. | | Signature placement | The signature is a direct child of the element it signs, and its reference points to that element’s ID. Scalekit reads assertions only from direct children of the response. These rules block XML signature-wrapping attacks. | | Issuer | The response and assertion issuer match the IdP entity ID configured on the connection. | | Audience | Any audience restriction in the assertion names the connection’s SP entity ID. | | Destination and recipient | The response destination and the subject confirmation recipient match the connection’s assertion consumer service (ACS) URL. | | Time conditions | `NotBefore` and `NotOnOrAfter` hold, with up to 180 seconds of clock skew. `IssueInstant` is within 90 seconds. | | Status | The response status is `Success`. | Scalekit also accepts encrypted assertions and decrypts them before validation. ### Replay protection [Section titled “Replay protection”](#replay-protection) Scalekit rejects a SAML response it has already accepted: * **SP-initiated sign-in:** the response’s `InResponseTo` must match a SAML request that Scalekit issued for the same browser, and each request ID can be used only once. * **IdP-initiated sign-in:** Scalekit stores the ID of each assertion it accepts and rejects an assertion with the same ID. Scalekit doesn’t send an authorization code to your app from an IdP-initiated response. It sends the user to your initiate-login URL, and your app starts a new SP-initiated sign-in. See [IdP-initiated SSO](/sso/guides/idp-init-sso/). ## PKCE on the authorization endpoint [Section titled “PKCE on the authorization endpoint”](#pkce-on-the-authorization-endpoint) Proof Key for Code Exchange (PKCE) stops a stolen authorization code from being redeemed by anyone else. Scalekit supports PKCE with the `S256` method on `/oauth/authorize`, the same endpoint your app uses to start SSO with `organization_id`, `connection_id`, `domain` or `login_hint`. | Request | PKCE parameters | | ---------------------- | ------------------------------------------------------------------------------------------------------------------ | | `GET /oauth/authorize` | `code_challenge`: the base64url-encoded SHA-256 hash of a random `code_verifier`. `code_challenge_method`: `S256`. | | `POST /oauth/token` | `code_verifier`: the value you hashed for `code_challenge`. | When the authorization request includes a `code_challenge`, the token request fails with `invalid_request` if `code_verifier` is missing, and with `invalid_grant` if it doesn’t match. ### Require PKCE for an application [Section titled “Require PKCE for an application”](#require-pkce-for-an-application) PKCE is required for single-page and native applications. To require it for a server-side app, register it as a web application: 1. In **Developers** > **Applications**, select **Create Application** and choose **Web Application**. 2. In the application’s settings, select **Enforce PKCE**. Scalekit then rejects authorization requests from that application that don’t include a code challenge. ## Organizations that share an identity provider [Section titled “Organizations that share an identity provider”](#organizations-that-share-an-identity-provider) Each SAML connection has its own SP entity ID, ACS URL and SP metadata URL, and each contains the connection’s ID. Scalekit identifies the connection from the ACS URL a response is posted to, not from the IdP’s entity ID. Two organizations can each have a SAML connection to the same IdP entity ID. The second connection doesn’t replace the first. In their IdP, the customer creates one SAML app per organization and enters that connection’s SP values in each. ## Directory sync (SCIM) [Section titled “Directory sync (SCIM)”](#directory-sync-scim) * **One endpoint and token per directory.** Each directory has its own SCIM endpoint URL and bearer token. Scalekit shows the token once, when it’s generated. Regenerate it to rotate it. * **Signed webhooks.** Every webhook Scalekit sends to your app is signed with your endpoint’s signing secret. Verify the signature and reject requests more than 5 minutes old. See [Verify webhook signatures](/guides/webhooks-best-practices/#verify-webhook-signatures). * **Recovery after downtime.** See [Recover from missed events](/guides/webhooks-best-practices/#recover-from-missed-events). ## Export connection configuration [Section titled “Export connection configuration”](#export-connection-configuration) Read a connection’s full configuration through the API with [Get a connection](/apis/#tag/connections). For a SAML connection, the response includes the IdP entity ID, SSO and logout URLs, metadata URL, bindings, signing options and the IdP certificates. Each certificate is the full base64-encoded certificate body, with its issue and expiry dates. Add `-----BEGIN CERTIFICATE-----` and `-----END CERTIFICATE-----` lines to use it as a PEM file. For an OIDC connection, the response includes the issuer, endpoint URLs, scopes and client ID. The client secret is masked. ## Certificate expiry and rotation [Section titled “Certificate expiry and rotation”](#certificate-expiry-and-rotation) Identity providers sign SAML responses with a certificate that expires on a date the IdP sets. How a rotation reaches Scalekit depends on how your customer configured the connection: * **With an IdP metadata URL (recommended)**: Scalekit reads the IdP’s metadata on every sign-in, so when your customer’s IdP switches to a new signing certificate, Scalekit uses it right away. Nobody needs to update the connection. * **With a manually entered certificate**: Scalekit uses the certificate saved on the connection. Once it expires, sign-in through the connection fails with `invalid_saml_metadata` until your customer’s IT admin enters the new certificate in the [admin portal](/authenticate/sso/admin-portal/), or you update the connection in the dashboard. ## Data residency [Section titled “Data residency”](#data-residency) Choose the region when you create your workspace. US workspaces run in Google Cloud `us-west2`, and EU workspaces run in `europe-west3`. Each region is a separate deployment with its own databases, and data isn’t replicated between them. SSO connection configuration, directory data, auth logs and backups for a workspace stay in its region. See [Choose a region](/dev-kit/guides/dashboard/environments/#choose-a-region-us-or-eu). ## Compliance reports [Section titled “Compliance reports”](#compliance-reports) * **SOC 2 Type II.** Scalekit is audited annually against the SOC 2 Security criteria. * **Penetration testing.** A third party tests Scalekit annually. * **Getting the reports.** Request the SOC 2 Type II report and the latest penetration test report from the [Scalekit Trust Center](https://trustcenter.scalekit.com). One mutual NDA covers both. * **HIPAA.** To sign a Business Associate Agreement (BAA), [contact us](/support/contact-us/). ## Dashboard access [Section titled “Dashboard access”](#dashboard-access) Only people your Admins invite can open your workspace in the Scalekit dashboard, and each person’s role controls what they can view or change. See [Team members and roles](/dev-kit/guides/dashboard/manage-team-members/). --- # DOCUMENT BOUNDARY --- # Introduction to Single Sign-on > Learn to basics of Single Sign-On (SSO), including how SAML and OIDC protocols work, and how Scalekit simplifies enterprise authentication. Single Sign-On (SSO) streamlines user access by enabling a single authentication event to grant access to multiple applications with the same credentials. For example, logging into one Google service, such as Gmail, automatically authenticates you to YouTube, Google Drive, and other Google platforms. There are two key benefits to the users and organizations with a secure single sign-on implementation: 1. User can seamlessly access multiple applications using only one set of credentials. 2. User credentials are managed in a centralized identity system. This enables Admins to easily configure and manage authentication policies for all their users from the centralized identity provider. Furthermore, this integrated SSO mechanism enhances user convenience, boosts productivity, and reduces the risks associated with password fatigue and reuse. These security & administration benefits are driving factors for enterprise organizations to only procure SaaS applications that offer SSO-based authentication. ## Understand how Single Sign-On works [Section titled “Understand how Single Sign-On works”](#understand-how-single-sign-on-works) Fundamentally, Single Sign-on works by exchanging user information in a pre-determined format between two trusted parties - your application and your customer’s identity provider (aka IdP). Most of these interactions happen in the browser context as some steps need user intervention. To ensure secure exchange of user information between your application and your customer’s identity provider, most IdPs support two protocols: Secure Assertion Markup Language (SAML) or OpenID Connect (OIDC). The objective of both these protocols is same: allow secure user information exchange between the Service Provider (your application) and Identity Provider (your customer’s identity system). These protocols differ in how these systems trust each other, communicate, and exchange user information. Let’s understand these protocols at a high level. ## Understanding SAML protocol [Section titled “Understanding SAML protocol”](#understanding-saml-protocol) SAML 2.0 (Secure Assertion Markup Language) has been in use since 2005 and is also most widely implemented protocol. SAML exchanges user information using XML files via HTTPS or SOAP. But, before the user information is exchanged between the two parties, they need to establish the trust between them. Trust is established by exchanging information about each other as part of SAML configuration parameters like Assertion Consumer Service URL (ACS URL), Entity ID, X.509 Certificates, etc. After the trust has been established, subsequent user information can be exchanged in two ways - 1. Your application requesting for a user’s information - this is Service Provider initiated login flow 2. Or the identity provider directly shares user details via a pre-configured ACS URL - this is Identity Provider initiated login flow Let’s understand these two SSO flows. ### Implement Service Provider initiated flow [Section titled “Implement Service Provider initiated flow”](#implement-service-provider-initiated-flow) ![SP initiated SSO workflow](/.netlify/images?url=_astro%2F1.DdT6sA5U.png\&w=3536\&h=2644\&dpl=6aedac7ec39c4cadbcd1959e) For service provider initiated SSO flow, 1. User tries to access your application and your app identifies that the user’s credentials need to be verified by their identity provider. 2. Your application requests the identity provider for the user’s information. 3. The identity provider authenticates the user and returns user details as “assertions” to your application. 4. You validate assertions, retrieve the user information, and if everything checks, allow the user to successfully login to your application. As you can imagine, in this workflow, the user login behaviour starts from your application and that’s why this is termed as service provider initiated SSO (aka SP-initiated SSO) ### Implement Identity Provider initiated flow [Section titled “Implement Identity Provider initiated flow”](#implement-identity-provider-initiated-flow) ![IdP initiated SSO workflow](/.netlify/images?url=_astro%2F2-idp-init-sso.CAu--K_L.png\&w=3536\&h=2168\&dpl=6aedac7ec39c4cadbcd1959e) In case of Identity Provider initiated SSO, 1. User logs into their identity provider portal and selects your application from within the IdP portal. 2. Identity Provider sends the user details as assertions to your application. 3. You validate assertions, retrieve the user information, and if everything checks, allow the user to successfully login to your application. Since the user login workflow starts from the Identity Provider portal (and not from your application), this flow is called Identity Provider initiated SSO (aka IdP-initiated SSO). #### Mitigate security risks [Section titled “Mitigate security risks”](#mitigate-security-risks) IdP initiated SSO is susceptible to common security attacks like Man In the Middle attack, Stolen Assertion attack or Assertion Replay attack etc. Read the [IdP initiated SSO](/sso/guides/idp-init-sso) guide to understand these risks and how to mitigate them. ## Understanding OIDC protocol [Section titled “Understanding OIDC protocol”](#understanding-oidc-protocol) OpenID Connect (OIDC) is an authentication protocol based on top of OAuth 2.0 to simplify the user information exchange process between Relying Party (your application) and the OpenID Provider (your customer’s Identity Provider). The OIDC protocol exchanges user information via signed JSON Web Tokens (JWT) over HTTPS. Because of the simplified nature of handling JWTs, it is often used in modern web applications, native desktop clients and mobile applications. With the latest extensions to the OIDC protocol like Proof Key of Code Exchange (PKCE) and Demonstrating Proof of Possession (DPoP), the overall security of user exchange information is strengthened. In its current format, OIDC only supports SP initiated Login. In this flow: 1. User tries to access your application. You identify that this user’s credentials need to be verified by their Identity Provider. 2. Your application requests the user’s Identity Provider for the user’s information via an OAuth2 request. 3. Identity Provider authenticates the user and sends the user’s details with an authorization_code to a pre-registered redirect_url on your server. 4. You will exchange the code for the actual user details by providing your information with the Identity provider. 5. Identity Provider will then send the user information in the form of JWTs. You retrieve the user information from those assertions and if everything is valid, you will allow the user inside your application. #### Simplify SSO with Scalekit [Section titled “Simplify SSO with Scalekit”](#simplify-sso-with-scalekit) Scalekit serves as an intermediary, abstracting the complexities involved in handling SSO with SAML and OIDC protocols. By integrating with Scalekit in just a few lines of code, your application can connect with numerous IdPs efficiently, ensuring security and compliance. --- # DOCUMENT BOUNDARY --- # Map IdP groups to roles in your app > Have your customer's identity provider send groups or a custom attribute, read them from the ID token in your SSO callback and set each user's role in your app. Enterprise customers want access in your app to follow their directory: people in their “App Admins” group are admins in your app, and someone removed from the group loses that access. With Modular SSO, your app keeps its own roles. Scalekit passes along what the customer’s identity provider (IdP) says about the user, and your app turns that into a role at each login. This page shows how to: 1. Turn on the attribute in Scalekit: the built-in **Groups** attribute, or a custom one. 2. Have your customer’s IT admin send it from their IdP. 3. Read it from the ID token in your callback and set the user’s role. It builds on the callback from [Handle the callback and find the user](/authenticate/sso/handle-callback/). ## Choose what the IdP sends [Section titled “Choose what the IdP sends”](#choose-what-the-idp-sends) | Attribute | What the IdP sends | Use it when | | -------------------------------------- | -------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------ | | **Groups** (`groups`) | A list of the user’s group names, which your app maps to roles | The customer already manages access with groups. Most IdPs, including Okta and Microsoft Entra ID, can send groups | | A custom attribute, such as `app_role` | One value that names the role in your app, such as `admin` | The customer would rather set a role per user, or their IdP can’t send groups | Your app can read both, as the code below does. ## Turn on the attribute [Section titled “Turn on the attribute”](#turn-on-the-attribute) Open **User Attributes** in the dashboard. * **Groups**: edit **Groups** and turn on its SSO mapping. It’s a built-in attribute that is off until you turn it on. * **A custom attribute**: select **Add Attribute**, enter an attribute name such as `app_role` and a display name, and save. Scalekit then reads an attribute or claim with the same name from the IdP. Attributes you don’t add here aren’t passed on, even if the IdP sends them. Don’t name a custom attribute after a [reserved name](#reserved-attribute-names) such as `roles`. ## Have the IdP send it [Section titled “Have the IdP send it”](#have-the-idp-send-it) Ask your customer’s IT admin to add the attribute to the app they created for your SSO connection: * **SAML**: an attribute named `groups`, or your custom attribute’s name, such as `app_role`. In Okta, that’s a group attribute statement; in Microsoft Entra ID, a group claim. * **OIDC**: a `groups` claim, or your custom attribute’s name, in the ID token or userinfo response. Microsoft Entra ID sends group IDs By default, Entra ID sends each group’s object ID, such as `5f3e…`, not its name. Map those IDs in your app, or ask the IT admin to send group names (cloud-only groups) or `sAMAccountName` (groups synced from on-premises Active Directory). The IT admin can check what their IdP sends with **Test Connection** in the [admin portal](/authenticate/sso/admin-portal/). The result lists the attributes Scalekit received. ## Set the role at each login [Section titled “Set the role at each login”](#set-the-role-at-each-login) The ID token from the code exchange carries `groups` as a list, and each custom attribute as a claim of its own. In your callback, after you validate the ID token, pass its claims to a function like this one and save the result on the user: * Node.js roles.js ```javascript 1 // Your app's role for each of a customer's IdP groups. Each customer names 2 // its groups differently, so keep this map per organization. 3 const GROUP_ROLES = { 4 '': { 'App Admins': 'admin', 'App Editors': 'editor' }, 5 }; 6 const ROLES_BY_RANK = ['admin', 'editor', 'viewer']; 7 8 function roleFor(claims) { 9 const groupRoles = GROUP_ROLES[claims.oid] ?? {}; 10 const groups = Array.isArray(claims.groups) ? claims.groups : []; 11 const roles = groups.map((group) => groupRoles[group]); 12 // A custom attribute that names the role directly, if you use one 13 if (ROLES_BY_RANK.includes(claims.app_role)) roles.push(claims.app_role); 14 // The highest role wins; a user in no mapped group gets the lowest 15 return ROLES_BY_RANK.find((role) => roles.includes(role)) ?? 'viewer'; 16 } 17 18 // In your callback, after: claims = await scalekit.validateToken(result.idToken); 19 // user.role = roleFor(claims); ``` * Python roles.py ```python 1 # Your app's role for each of a customer's IdP groups. Each customer names 2 # its groups differently, so keep this map per organization. 3 GROUP_ROLES = { 4 "": {"App Admins": "admin", "App Editors": "editor"}, 5 } 6 ROLES_BY_RANK = ["admin", "editor", "viewer"] 7 8 9 def role_for(claims): 10 group_roles = GROUP_ROLES.get(claims.get("oid"), {}) 11 groups = claims.get("groups") 12 roles = [group_roles.get(group) for group in groups] if isinstance(groups, list) else [] 13 # A custom attribute that names the role directly, if you use one 14 if claims.get("app_role") in ROLES_BY_RANK: 15 roles.append(claims["app_role"]) 16 # The highest role wins; a user in no mapped group gets the lowest 17 return next((role for role in ROLES_BY_RANK if role in roles), "viewer") 18 19 20 # In your callback: 21 # claims = scalekit_client.validate_token(result["id_token"]) 22 # user.role = role_for(claims) ``` * Go roles.go ```go 1 package main 2 3 import "slices" 4 5 // Your app's role for each of a customer's IdP groups. Each customer names 6 // its groups differently, so keep this map per organization. 7 var groupRoles = map[string]map[string]string{ 8 "": {"App Admins": "admin", "App Editors": "editor"}, 9 } 10 11 var rolesByRank = []string{"admin", "editor", "viewer"} 12 13 func roleFor(claims map[string]interface{}) string { 14 orgID, _ := claims["oid"].(string) 15 var roles []string 16 groups, _ := claims["groups"].([]interface{}) 17 for _, g := range groups { 18 if group, ok := g.(string); ok { 19 roles = append(roles, groupRoles[orgID][group]) 20 } 21 } 22 // A custom attribute that names the role directly, if you use one 23 if appRole, ok := claims["app_role"].(string); ok && slices.Contains(rolesByRank, appRole) { 24 roles = append(roles, appRole) 25 } 26 // The highest role wins; a user in no mapped group gets the lowest 27 for _, role := range rolesByRank { 28 if slices.Contains(roles, role) { 29 return role 30 } 31 } 32 return "viewer" 33 } 34 35 // In your callback, after: 36 // claims, err := scalekitClient.ValidateToken(r.Context(), result.IdToken) 37 // user.Role = roleFor(claims) ``` * Java Roles.java ```java 1 import java.util.ArrayList; 2 import java.util.List; 3 import java.util.Map; 4 5 public class Roles { 6 // Your app's role for each of a customer's IdP groups. Each customer names 7 // its groups differently, so keep this map per organization. 8 static final Map> GROUP_ROLES = Map.of( 9 "", Map.of("App Admins", "admin", "App Editors", "editor")); 10 static final List ROLES_BY_RANK = List.of("admin", "editor", "viewer"); 11 12 static String roleFor(Map claims) { 13 Map groupRoles = GROUP_ROLES.getOrDefault((String) claims.get("oid"), Map.of()); 14 List roles = new ArrayList<>(); 15 if (claims.get("groups") instanceof List groups) { 16 for (Object group : groups) { 17 roles.add(groupRoles.get(String.valueOf(group))); 18 } 19 } 20 // A custom attribute that names the role directly, if you use one 21 if (claims.get("app_role") instanceof String appRole && ROLES_BY_RANK.contains(appRole)) { 22 roles.add(appRole); 23 } 24 // The highest role wins; a user in no mapped group gets the lowest 25 return ROLES_BY_RANK.stream().filter(roles::contains).findFirst().orElse("viewer"); 26 } 27 } 28 29 // In your callback, after: 30 // claims = scalekitClient.authentication().validateAccessTokenAndGetClaims(result.getIdToken()); 31 // user.setRole(Roles.roleFor(claims)); ``` Keep these rules in the function: * **Set the role at every login, not only the first.** When the IT admin removes someone from a group, the change reaches your app at the user’s next login. * **Map groups per organization.** One customer’s “Admins” group says nothing about another’s. The ID token’s `oid` claim tells you whose groups they are. * **Accept only roles your app defines.** Ignore groups and values you haven’t mapped, and give users with none the lowest role. ## Check it worked [Section titled “Check it worked”](#check-it-worked) 1. Add a custom attribute named `app_role`, as in [Turn on the attribute](#turn-on-the-attribute). 2. Start a login for your test organization. In the SSO simulator, select **+ Add Attribute**, enter `app_role` as the key and `admin` as the value, and select **Simulate Login**. 3. Your callback’s ID token claims include `"app_role": "admin"`, and the user’s role is `admin`. The simulator sends each value as text, so test **Groups** with a real IdP, such as a free Okta developer account. ## Reserved attribute names [Section titled “Reserved attribute names”](#reserved-attribute-names) These names are used by Scalekit. A custom attribute with one of them is dropped or overwritten: | Name | Use | | ----------------------------------- | --------------------------------------------------------------------------------------------------------------------------------- | | `roles`, `permissions` | Roles and permissions in Scalekit’s full-stack auth. In Modular SSO, send groups or a custom attribute such as `app_role` instead | | `email`, `email_verified` | Standard email claims | | `name`, `given_name`, `family_name` | Standard profile claims | | `sub`, `oid`, `sid` | Scalekit identifiers | ## Next [Section titled “Next”](#next) * [Normalized user profile](/sso/guides/user-profile-details/): the fields your callback receives, including the IdP’s raw attributes. * [Onboard an enterprise customer](/sso/guides/onboard-enterprise-customers/): create their organization and give their IT admin the admin portal. --- # DOCUMENT BOUNDARY --- # SSO simulator > Test Enterprise SSO based authentication using our SSO Simulator without configuring SAML or OIDC based SSO with a real IdP After implementing Single Sign-On using our [Quickstart guide](/authenticate/sso/add-modular-sso/), you need to validate your integration for all possible scenarios. This guide shows you how to test your SSO implementation using two approaches: 1. **SSO Simulator (quick testing):** Test all SSO scenarios without external services. Your development environment includes a pre-configured test organization with an SSO connection to our SSO Simulator. 2. **Real identity provider (production-ready testing):** Test with actual identity providers like Okta or Microsoft Entra ID to simulate real customer scenarios. To ensure a successful SSO implementation, test all three scenarios described in this guide before deploying to production: SP-initiated SSO, IdP-initiated SSO, and error handling. ## Testing with SSO Simulator Quick testing [Section titled “Testing with SSO Simulator ”](#testing-with-sso-simulator-) The SSO Simulator allows you to test all SSO scenarios without requiring external services. Your development environment includes a pre-configured test organization with an SSO connection to our SSO Simulator and test domains like `@example.com` or `@example.org`. To locate the test organization, navigate to **Dashboard > Organizations** and select **Test Organization**. ![Test Organization](/.netlify/images?url=_astro%2F2.CCYEcEtj.png\&w=2786\&h=1746\&dpl=6aedac7ec39c4cadbcd1959e) ### Service provider (SP) initiated SSO Scenario 1 [Section titled “Service provider (SP) initiated SSO ”](#service-provider-sp-initiated-sso-) In this common scenario, users start the Single Sign-On process from your application’s login page. ![SP initiated SSO](/.netlify/images?url=_astro%2F1.Bn8Ae4ZM.png\&w=4936\&h=3744\&dpl=6aedac7ec39c4cadbcd1959e) #### Generate authorization URL [Section titled “Generate authorization URL”](#generate-authorization-url) Generate an authorization URL with your test organization ID. This redirects users to Scalekit’s hosted login page, which will then redirect to the SSO Simulator. * Node.js Express.js ```javascript // Use your test organization ID from the dashboard const options = { organizationId: 'org_32656XXXXXX0438' // Replace with your test organization ID }; // Generate Authorization URL that redirects to SSO Simulator const authorizationURL = scalekit.getAuthorizationUrl(redirectUrl, options); // Redirect user to start SSO flow res.redirect(authorizationURL); ``` * Python Flask ```python from scalekit import AuthorizationUrlOptions # Use your test organization ID from the dashboard options = AuthorizationUrlOptions() options.organization_id = 'org_32656XXXXXX0438' # Replace with your test organization ID # Generate Authorization URL that redirects to SSO Simulator authorization_url = scalekit_client.get_authorization_url( redirect_url, options, ) # Redirect user to start SSO flow return redirect(authorization_url) ``` * Go Gin ```go 1 // Use your test organization ID from the dashboard 2 options := scalekit.AuthorizationUrlOptions{ 3 OrganizationId: "org_32656XXXXXX0438", // Replace with your test organization ID 4 } 5 6 // Generate Authorization URL that redirects to SSO Simulator 7 authorizationURL, err := scalekitClient.GetAuthorizationUrl( 8 redirectUrl, 9 options, 10 ) 11 if err != nil { 12 c.AbortWithError(http.StatusInternalServerError, err) 13 return 14 } 15 16 // Redirect user to start SSO flow 17 c.Redirect(http.StatusFound, authorizationURL.String()) ``` * Java Spring Boot ```java // Use your test organization ID from the dashboard AuthorizationUrlOptions options = new AuthorizationUrlOptions(); options.setOrganizationId("org_32656XXXXXX0438"); // Replace with your test organization ID // Generate Authorization URL that redirects to SSO Simulator String authorizationURL = scalekitClient .authentication() .getAuthorizationUrl(redirectUrl, options) .toString(); // Redirect user to start SSO flow return "redirect:" + authorizationURL; ``` #### Test the SSO flow [Section titled “Test the SSO flow”](#test-the-sso-flow) After generating the authorization URL, users are redirected to the SSO Simulator: 1. Select **User login via SSO** from the dropdown menu 2. Enter test user details (email, name, etc.) to simulate authentication 3. Click **Submit** to complete the simulation ![SSO Simulator form](/.netlify/images?url=_astro%2F2.1.BEM1Vo-J.png\&w=2646\&h=1652\&dpl=6aedac7ec39c4cadbcd1959e) After submitting the form, your application receives an `idToken` containing the user details you entered: ![ID token response](/.netlify/images?url=_astro%2F2.2.tePTMu6U.png\&w=2182\&h=1146\&dpl=6aedac7ec39c4cadbcd1959e) ### Identity provider (IdP) initiated SSO Scenario 2 [Section titled “Identity provider (IdP) initiated SSO ”](#identity-provider-idp-initiated-sso-) In this scenario, users start the sign-in process from their identity provider (typically through an applications catalog) rather than from your application’s login page. Your application must handle this flow by detecting IdP-initiated requests and converting them to SP-initiated SSO. If you haven’t implemented IdP-initiated SSO yet, follow our [IdP-initiated SSO implementation guide](/sso/guides/idp-init-sso) before testing this scenario. ![How IdP-initiated SSO works](/.netlify/images?url=_astro%2F4.DI1M7pT-.png\&w=4936\&h=4432\&dpl=6aedac7ec39c4cadbcd1959e) #### Test IdP-initiated SSO flow [Section titled “Test IdP-initiated SSO flow”](#test-idp-initiated-sso-flow) 1. Generate the authorization URL using your test organization 2. When redirected to the SSO Simulator, select **IdP initiated SSO** from the dropdown menu 3. Enter test user details to simulate the login 4. Click **Submit** to complete the simulation ![IdP initiated SSO form](/.netlify/images?url=_astro%2F3.1.CmRUnvaS.png\&w=2530\&h=1656\&dpl=6aedac7ec39c4cadbcd1959e) #### Verify callback handling [Section titled “Verify callback handling”](#verify-callback-handling) Your callback handler receives the IdP-initiated request and must process it correctly: ![IdP initiated callback](/.netlify/images?url=_astro%2F3.2.D4V_v_y-.png\&w=2024\&h=486\&dpl=6aedac7ec39c4cadbcd1959e) Your application should: 1. Detect the IdP-initiated request based on the request parameters 2. Retrieve connection details (`connection_id` or `organization_id`) from Scalekit 3. Generate a new authorization URL to convert the IdP-initiated flow to SP-initiated SSO 4. Complete the authentication flow ### Error handling Scenario 3 [Section titled “Error handling ”](#error-handling-) Your application should gracefully handle error scenarios to provide a good user experience. SSO failures can occur due to misconfiguration, incomplete user profiles, or integration issues. #### Test error scenarios [Section titled “Test error scenarios”](#test-error-scenarios) 1. Generate and redirect to the authorization URL 2. In the SSO Simulator, select **Error** from the dropdown menu 3. Verify your callback handler processes the error correctly 4. Ensure users see an appropriate error message ![Error scenario in SSO Simulator](/.netlify/images?url=_astro%2F5.DIgPtBxP.png\&w=2364\&h=1216\&dpl=6aedac7ec39c4cadbcd1959e) ## Testing with real identity providers Production-ready [Section titled “Testing with real identity providers ”](#testing-with-real-identity-providers-) After validating your SSO implementation with the SSO Simulator, test with real identity providers like Okta or Microsoft Entra ID to simulate actual customer scenarios. This ensures your integration works correctly with production identity systems. ### Setup your test environment [Section titled “Setup your test environment”](#setup-your-test-environment) To simulate a real customer onboarding scenario, create a new organization with a real SSO connection: 1. Create an organization at **Dashboard > Organizations** with a name that reflects a test customer 2. Generate an **Admin Portal link** from the organization’s overview page 3. Open the Admin Portal link and follow the integration guide to set up an SSO connection: * [Okta SAML integration guide](/guides/integrations/sso-integrations/okta-saml/) * [Microsoft Entra ID integration guide](/guides/integrations/sso-integrations/azure-ad-saml/) * [Other SSO integrations](/guides/integrations/) ### Service provider (SP) initiated SSO Scenario 1 [Section titled “Service provider (SP) initiated SSO ”](#service-provider-sp-initiated-sso--1) Test the most common SSO scenario where users start the authentication flow from your application’s login page. ![SP initiated SSO workflow](/.netlify/images?url=_astro%2F1.Bn8Ae4ZM.png\&w=4936\&h=3744\&dpl=6aedac7ec39c4cadbcd1959e) #### Validate the flow [Section titled “Validate the flow”](#validate-the-flow) 1. **Generate authorization URL**: Create an authorization URL with your test organization’s ID (see [Authorization URL documentation](/sso/guides/authorization-url/)) 2. **User authentication**: Verify that Scalekit redirects users to the correct identity provider 3. **Callback handling**: Confirm your application receives the authorization code at your redirect URI 4. **Token exchange**: Verify you can exchange the authorization code for user details and tokens 5. **Session creation**: Ensure your application creates a session and logs the user in successfully Your application should successfully retrieve user details including email, name, and any custom attributes configured in the SSO connection. ### Identity provider (IdP) initiated SSO Scenario 2 [Section titled “Identity provider (IdP) initiated SSO ”](#identity-provider-idp-initiated-sso--1) Test the scenario where users start authentication from their identity provider’s application catalog. ![IdP-initiated SSO workflow](/.netlify/images?url=_astro%2Fidp-initiated-sso.v3FnpBpw.png\&w=3536\&h=2168\&dpl=6aedac7ec39c4cadbcd1959e) #### Validate the flow [Section titled “Validate the flow”](#validate-the-flow-1) 1. **Initial callback**: User is redirected to your default redirect URI with IdP-initiated request parameters 2. **Detection logic**: Your application detects this as an IdP-initiated request (based on the request parameters) 3. **SP-initiated conversion**: Your application initiates SP-initiated SSO by generating an authorization URL 4. **IdP redirect**: User is redirected to the identity provider based on the authorization URL 5. **Final callback**: After authentication, user is redirected back with an authorization code and state parameter 6. **Token exchange**: Exchange the code for user details and complete the login For implementation details, see our [IdP-initiated SSO implementation guide](/sso/guides/idp-init-sso/). Default redirect URL configuration Ensure your default redirect URL is correctly configured at **Dashboard > Developers > Redirect URLs**. This URL receives IdP-initiated requests. ### Error handling Scenario 3 [Section titled “Error handling ”](#error-handling--1) Test how your application handles SSO failures. Common error scenarios include: * Misconfigured SSO connections (wrong certificates, invalid metadata) * Incomplete user profiles (missing required attributes) * Expired or revoked SSO connections * Network or integration issues with the identity provider #### Validate error handling [Section titled “Validate error handling”](#validate-error-handling) 1. Review the [SSO integration error codes](/sso/reference/sso-integration-errors/) documentation 2. Test each applicable error scenario by intentionally misconfiguring your SSO connection 3. Verify your application displays appropriate, user-friendly error messages 4. Ensure errors are logged for debugging purposes 5. Confirm users can retry authentication or contact support ## Next steps [Section titled “Next steps”](#next-steps) After thoroughly testing your SSO implementation: 1. Review the [SSO launch checklist](/sso/guides/launch-checklist/) to ensure production readiness 2. Configure the [Admin Portal](/authenticate/sso/admin-portal/) for your customers to self-serve SSO setup 3. Implement [custom domain](/authenticate/sso/custom-domain/) for a seamless branded experience 4. Set up [webhooks](/authenticate/sso/webhooks/) to receive real-time authentication events --- # DOCUMENT BOUNDARY --- # Normalized user profile > Learn how Scalekit's normalized user profiles standardize identity data across providers, streamlining single sign-on (SSO) integration and user management. When a user logs in with SSO, each identity provider shares the user profile information in their own format. This adds complexity for the application developers to parse the user profile info and code related identity workflows. To make this seamless for developers, Scalekit normalizes the user profile info into a standard set of fields across all identity providers. This means that you’d always receive the user profile payload in a fixed set of fields, irrespective of the identity provider and protocol you interact with. This is one of our foundational aspects of the unified SSO solution. Sample normalized user profile ```json 1 { 2 "email": "john.doe@acmecorp.com", 3 "email_verified": true, 4 "family_name": "Doe", 5 "given_name": "John", 6 "locale": "en", 7 "name": "John Doe", 8 "picture": "https://lh3.googleusercontent.com/a/ACg8ocKNE4TZ...iEma17URCEf=s96-c", 9 "sub": "conn_17576372041941092;google-oauth2|104630259163176101050", 10 "identities": [ 11 { 12 "connection_id": "conn_17576372041941092", 13 "organization_id": "org_17002852291444836", 14 "connection_type": "OIDC", 15 "provider_name": "AUTH0", 16 "social": false, 17 "provider_raw_attributes": { 18 "aud": "ztTgHijLLguDXJQab0oiPyIcDLXXrJX6", 19 "email": "john.doe@acmecorp.com", 20 "email_verified": true, 21 "exp": 1714580633, 22 "family_name": "Doe", 23 "given_name": "John", 24 "iat": 1714544633, 25 "iss": "https://dev-rmmfmus2g7vverbf.us.auth0.com/", 26 "locale": "en", 27 "name": "John Doe", 28 "nickname": "john.doe", 29 "nonce": "Lof9SpxEzs9dhUlJzgrrbQ==", 30 "picture": "https://lh3.googleusercontent.com/a/ACg8ocKNE4T...17URCEf=s96-c", 31 "sid": "5yqRJIfjPh8c7lr1s2N-IbY6WR8VyaIZ", 32 "sub": "google-oauth2|104630259163176101050", 33 "updated_at": "2024-04-30T10:02:30.988Z" 34 } 35 } 36 ] 37 } ``` ## Full list of user profile attributes [Section titled “Full list of user profile attributes”](#full-list-of-user-profile-attributes) | Profile attribute | Data type | Description | | ----------------- | ----------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------- | | `sub` | string | The connection ID and the user’s ID at the identity provider, joined by `;`. See [How `sub` is built](#how-sub-is-built). | | `email` | string | The user’s email address. | | `email_verified` | boolean | True if the user’s e-mail address has been verified as claimed by the identity provider; otherwise false. | | `name` | string | Fully formatted user’s name | | `family_name` | string | The user’s surname or last name. | | `given_name` | string | The user’s given name or first name. | | `locale` | string | The user’s locale, represented by a BCP 47 language tag. Example: ‘en’ | | `picture` | string | The user’s profile picture in URL format | | `identities` | Array of [Identity objects](/sso/guides/user-profile-details/#identity-object-attributes) | Array of all identity information received from the identity providers in the raw format | ### Identity object attributes [Section titled “Identity object attributes”](#identity-object-attributes) | Identity attribute | Data type | Description | | ------------------------- | --------- | ----------------------------------------------------------------------------------------------------- | | `organization_id` | string | Unique ID of the organization to which this user belongs to | | `connection_id` | string | Unique ID of the connection for which this identity data is fetched from | | `connection_type` | string | type of the connection: SAML or OIDC | | `provider_name` | string | name of the connection provider. Example: Okta, Google, Auth0 | | `social` | boolean | Is the connection a social provider (like Google, Microsoft, GitHub etc) or an enterprise connection. | | `provider_raw_attributes` | object | key-value map of all the raw attributes received from the connection provider as-is | ## How `sub` is built [Section titled “How sub is built”](#how-sub-is-built) `sub` has the form `;`, for example `conn_17576372041941092;00u1a2b3c4d5e6f7g8h9`. The IdP user ID depends on the connection type: | Connection type | IdP user ID in `sub` | | --------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | SAML | The `NameID` value in the assertion’s `Subject`. Scalekit rejects a SAML response without a `NameID` with `mandatory_attribute_missing`, so `sub` is always present. | | OIDC | The `sub` claim from the identity provider. | ## What `provider_raw_attributes` contains [Section titled “What provider_raw_attributes contains”](#what-provider_raw_attributes-contains) `provider_raw_attributes` holds the identity provider’s data before Scalekit maps it to the fields above: * **SAML**: every attribute in the assertion’s attribute statements, keyed by the attribute `Name` exactly as the IdP sent it, plus the `NameID` under the key `nameid`. An attribute with one value is a string; an attribute with several values, and `groups`, is an array. * **OIDC**: every claim in the identity provider’s ID token. For some providers, such as Okta, Scalekit reads the claims from the provider’s userinfo endpoint instead, because their ID tokens leave out attributes like groups. ## Choose a stable user identifier [Section titled “Choose a stable user identifier”](#choose-a-stable-user-identifier) Store the identifier that stays the same for a user across sign-ins: * **Key users on the organization and the IdP user ID**, not on the full `sub`. `sub` starts with the connection ID, so it changes if your customer deletes their SSO connection and creates a new one. * **Check which value the IdP sends as the user ID.** A SAML `NameID` in persistent format, or an OIDC `sub`, stays the same for a user. A `NameID` that holds an email address or user principal name changes when the user is renamed. ### Microsoft Entra ID [Section titled “Microsoft Entra ID”](#microsoft-entra-id) * **SAML**: Entra ID sends the user principal name as the `NameID` by default. Use the object ID instead: read it from the `http://schemas.microsoft.com/identity/claims/objectidentifier` attribute in `provider_raw_attributes`, or ask your customer to set the **Unique User Identifier (Name ID)** claim to `user.objectid` in their Entra ID app. * **OIDC**: Entra ID’s `sub` claim is unique to each app registration. To match the same user across apps, or with directory data, read the `oid` claim from `provider_raw_attributes`. It’s the user’s object ID in Entra ID. --- # DOCUMENT BOUNDARY --- # SSO connection events > Webhook events Scalekit sends when an organization's SSO connection is created, enabled, disabled or deleted, with sample payloads and fields. Scalekit sends a webhook when an organization’s SSO connection is created, enabled, disabled or deleted. Use these events to keep your app’s record of which organizations can sign in with SSO in step with Scalekit, for example to show or hide an SSO button or to require SSO for an organization’s users. To receive them, add an endpoint in **Developers** > **Webhooks** and select the events. See [Implement webhooks](/authenticate/sso/webhooks/), and verify every delivery as described in [Verify webhook signatures](/guides/webhooks-best-practices/#verify-webhook-signatures). | Event | Sent when | | -------------------------------------------------------- | ----------------------------------------------------------------------------- | | [`organization.sso_created`](#organizationsso_created) | An SSO connection is created for an organization | | [`organization.sso_enabled`](#organizationsso_enabled) | An SSO connection is enabled, so the organization’s users can sign in with it | | [`organization.sso_disabled`](#organizationsso_disabled) | An SSO connection is disabled, so its users can no longer sign in with it | | [`organization.sso_deleted`](#organizationsso_deleted) | An SSO connection is deleted | Scalekit doesn’t send a webhook when a connection’s configuration changes, such as its IdP metadata, certificate or attribute mapping. To read a connection’s current configuration, call [Get connection details](/apis/#tag/connections). For how IdP certificate rotation works, see [Certificate expiry and rotation](/sso/guides/security-and-compliance/#certificate-expiry-and-rotation). ## Event envelope [Section titled “Event envelope”](#event-envelope) Every SSO connection event has the same top-level fields. The connection is in `data`. Keys can arrive in any order, so parse the body as JSON rather than matching it as text. | Field | Type | Description | | ----------------- | ------ | ---------------------------------------------------------------------------- | | `spec_version` | string | Webhook payload version. Currently `"1"` | | `id` | string | Unique event ID, prefixed with `evt_`. Use it to ignore duplicate deliveries | | `type` | string | Event type, such as `organization.sso_enabled` | | `occurred_at` | string | When the event occurred, in RFC 3339 format | | `environment_id` | string | Environment the event belongs to | | `organization_id` | string | Organization the connection belongs to | | `object` | string | Always `Connection` | | `data` | object | The connection. All four events carry the same fields | ### Connection fields in `data` [Section titled “Connection fields in data”](#connection-fields-in-data) | Field | Type | Description | | ----------------- | --------------- | ----------------------------------------------------------------------------------------------------------- | | `id` | string | Connection ID, prefixed with `conn_`. It’s the `connection_id` you pass in an authorization URL | | `organization_id` | string | Organization that owns the connection | | `connection_type` | string | `SAML` or `OIDC` | | `provider` | string | Identity provider, such as `OKTA` or `MICROSOFT_AD` | | `enabled` | boolean or null | Whether users can sign in with the connection. `null` when the value wasn’t recorded with the event | | `status` | string or null | Setup progress: `DRAFT`, `IN_PROGRESS` or `COMPLETED`. `null` when the value wasn’t recorded with the event | ## `organization.sso_created` [Section titled “organization.sso_created”](#organizationsso_created) Sent when an SSO connection is created for an organization, from the dashboard, the admin portal or the API. A new connection is usually disabled and in `DRAFT` until your customer’s IT admin finishes setup and enables it. organization.sso_created ```json 1 { 2 "spec_version": "1", 3 "id": "evt_94567862441607493", 4 "type": "organization.sso_created", 5 "occurred_at": "2025-10-14T09:27:18.488720586Z", 6 "environment_id": "env_74418471961625391", 7 "organization_id": "org_83544995172188677", 8 "object": "Connection", 9 "data": { 10 "id": "conn_94567862424830277", 11 "organization_id": "org_83544995172188677", 12 "connection_type": "OIDC", 13 "provider": "OKTA", 14 "enabled": false, 15 "status": "DRAFT" 16 } 17 } ``` ## `organization.sso_enabled` [Section titled “organization.sso_enabled”](#organizationsso_enabled) Sent when an SSO connection is enabled. From now on, the organization’s users can sign in through it. organization.sso_enabled ```json 1 { 2 "spec_version": "1", 3 "id": "evt_94568078213382471", 4 "type": "organization.sso_enabled", 5 "occurred_at": "2025-10-14T09:29:27.098914861Z", 6 "environment_id": "env_74418471961625391", 7 "organization_id": "org_83544995172188677", 8 "object": "Connection", 9 "data": { 10 "id": "conn_94567862424830277", 11 "organization_id": "org_83544995172188677", 12 "connection_type": "OIDC", 13 "provider": "OKTA", 14 "enabled": true, 15 "status": "COMPLETED" 16 } 17 } ``` ## `organization.sso_disabled` [Section titled “organization.sso_disabled”](#organizationsso_disabled) Sent when an SSO connection is disabled. Sign-in requests that target this connection now fail with `connection_not_active` or `no_active_connections` (see the [error reference](/sso/reference/sso-integration-errors/)), so route the organization’s users to another sign-in method until it’s enabled again. organization.sso_disabled ```json 1 { 2 "spec_version": "1", 3 "id": "evt_94557976165089560", 4 "type": "organization.sso_disabled", 5 "occurred_at": "2025-10-14T07:49:05.809554456Z", 6 "environment_id": "env_74418471961625391", 7 "organization_id": "org_83544995172188677", 8 "object": "Connection", 9 "data": { 10 "id": "conn_83545002856153607", 11 "organization_id": "org_83544995172188677", 12 "connection_type": "OIDC", 13 "provider": "OKTA", 14 "enabled": false, 15 "status": "COMPLETED" 16 } 17 } ``` ## `organization.sso_deleted` [Section titled “organization.sso_deleted”](#organizationsso_deleted) Sent when an SSO connection is deleted. If your customer creates a new connection, it has a new connection ID, so the `sub` of their users changes. See [Choose a stable user identifier](/sso/guides/user-profile-details/#choose-a-stable-user-identifier). organization.sso_deleted ```json 1 { 2 "spec_version": "1", 3 "id": "evt_94557997639926040", 4 "type": "organization.sso_deleted", 5 "occurred_at": "2025-10-14T07:49:18.604546332Z", 6 "environment_id": "env_74418471961625391", 7 "organization_id": "org_83544995172188677", 8 "object": "Connection", 9 "data": { 10 "id": "conn_83545002856153607", 11 "organization_id": "org_83544995172188677", 12 "connection_type": "OIDC", 13 "provider": "OKTA", 14 "enabled": false, 15 "status": "COMPLETED" 16 } 17 } ``` --- # DOCUMENT BOUNDARY --- # Error handling during single sign-on > Learn how to identify and resolve common single sign-on errors in Scalekit, ensuring a seamless authentication experience for your users Reference of error codes and how to handle them. For step-by-step fixes of the errors developers hit most often while adding Modular SSO, see [Troubleshoot Modular SSO](/authenticate/sso/troubleshooting/). When users attempt to log in via single sign-on (SSO) using Scalekit, any issues encountered will result in error details being sent to your application’s redirect URI via the `error` and `error_description` query parameters. Proper error handling ensures a better user experience. ## Where Scalekit sends errors [Section titled “Where Scalekit sends errors”](#where-scalekit-sends-errors) Scalekit sends an SSO error to the `redirect_uri` of the sign-in request, the same URL that receives the authorization code on success. The redirect carries `error`, `error_description` and the `state` value from your [authorization URL](/sso/guides/authorization-url/). If the `redirect_uri` is missing or isn’t one of your registered redirect URLs, Scalekit can’t redirect and shows the user an error page instead. Errors from [IdP-initiated sign-in](/sso/guides/idp-init-sso/) have no sign-in request to return to, so Scalekit sends them to your initiate-login URL with the same `error` and `error_description` parameters. ### Show an organization-specific error page [Section titled “Show an organization-specific error page”](#show-an-organization-specific-error-page) Errors don’t have a per-connection destination, but you choose the `redirect_uri` and `state` on every sign-in request, so your callback knows which organization the user was signing in to. Use that to show an error page that fits the organization and tells its users how to fix the problem. * **Look up the organization from `state`.** When you build the authorization URL, store the organization ID in the user’s server-side session next to the random `state` value. In your callback, verify `state` matches, read the organization ID from the session, and render that organization’s error page. * **Or use a redirect URL per organization.** Register a separate redirect URL for each organization, such as `https://app.example.com/sso/callback/acme`, and pass it as `redirect_uri` on that organization’s sign-in requests. Keep `state` unguessable and verify it on every callback, including error callbacks. Don’t put the organization ID in `state` in place of the random value: `state` protects the callback from cross-site request forgery. ## Integration related errors [Section titled “Integration related errors”](#integration-related-errors) If there is any issue between Scalekit and your application, the following errors may occur: | Error | Error description | Possible resolution strategy | | ----------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | ``` invalid_redirect_uri ``` | Redirect URI is not part of the pre-approved list of redirect URIs | Add the valid URL in the Scalekit dashboard before using it | | ``` invalid_connection_selector ``` | The authorization URL has no `organization_id`, `connection_id`, `domain` or `login_hint`, or the one it has doesn’t match an organization, connection or domain in this environment | Pass one of these parameters, with an ID from the same environment as your API credentials. See [Troubleshooting](/authenticate/sso/troubleshooting/#invalid_connection_selector) | | ``` no_active_connections ``` | There are no active SSO connections configured to process the single sign-on request | Ensure active SSO connections are set up | | ``` connection_not_active ``` | The configured connection is not active | Enable the SSO connection in the Scalekit dashboard | | ``` no_configured_connections ``` | No active SSO connections configured | Ensure active SSO connections are set up | | ``` invalid_organization_id ``` | Invalid organization ID | Verify and use a valid organization ID | | ``` invalid_connection_id ``` | Invalid connection ID | Verify and use a valid connection ID | | ``` domain_not_found ``` | No domain specified for the SSO connection(s) | Check domain configuration in Scalekit dashboard | | ``` invalid_user_domain ``` | User’s domain not allowed for this SSO connection | Ensure user domain is part of the allowed domains list | | ``` invalid_client ``` | The client application is not recognized or not configured correctly | Verify the `client_id` value in your authorization URL | | ``` application_not_active ``` | The application is inactive | Enable the application in the Scalekit dashboard | | ``` invalid_request ``` | The authorization request contains invalid or missing parameters, such as no `scope` | Review the authorization URL parameters | | ``` invalid_idp_initiated_sso ``` | A user started from their IdP’s dashboard, and the environment has no initiate login URL | Build an [initiate login endpoint](/sso/guides/idp-init-sso/) and register it under **Authentication** > **Redirect URLs** | | ``` unauthorized ``` | The request is unauthorized | Verify that valid credentials are being used | | ``` user_not_active ``` | The user account is inactive | Activate the user account or contact the IT admin | | ``` server_error ``` | *actual error description from the server* | This must be a rare occurrence. Please reach out to us via your private slack channel or [via email](mailto:support@scalekit.com) | ## SSO configuration related errors [Section titled “SSO configuration related errors”](#sso-configuration-related-errors) If SSO configuration issues arise, you will encounter the following errors: | Error code | Error description | Possible resolution strategy | | ------------------------------------ | --------------------------------------------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | ``` mandatory_attribute_missing ``` | Missing mandatory user attributes | Ensure all the mandatory user attributes are configured properly | | ``` invalid_id_token ``` | Invalid ID token | Check the identity provider’s functioning | | ``` failed_to_exchange_token ``` | Token exchange failure due to incorrect `client_secret` | Update the `client_secret` with the correct value | | ``` user_info_retrieve_failed ``` | User info retrieval failed, possibly due to an incorrect `client_secret` or other issues | Update the `client_secret` with the correct value. If unsuccessful, investigate further. Please reach out to us via your private slack channel or [via email](mailto:support@scalekit.com) | | ``` invalid_saml_metadata ``` | Scalekit couldn’t use the IdP’s SAML metadata or certificate. A common cause is an expired IdP signing certificate | Check the metadata URL is correct and reachable. If the connection uses a manually entered certificate, enter the IdP’s current signing certificate. See [Certificate expiry and rotation](/sso/guides/security-and-compliance/#certificate-expiry-and-rotation) | | ``` invalid_saml_response ``` | Invalid SAML response | Review and fix SAML configuration settings | | ``` invalid_in_response_to ``` | The SAML response doesn’t match a login started in this browser, for example because an embedded web view dropped cookies or two logins ran at once | Open SSO logins in the system browser, one at a time. See [Troubleshooting](/authenticate/sso/troubleshooting/#invalid_in_response_to) | | ``` invalid_saml_request ``` | The SAML request is invalid | Check the SAML configuration in both Scalekit and the identity provider | | ``` invalid_saml_form_params ``` | The SAML form parameters are invalid or malformed | Review the SAML response format from the identity provider | | ``` signature_validation_failed ``` | Failed signature validation | Review and update the ACS URL in the identity provider’s settings | | ``` invalid_acs_url ``` | Invalid ACS URL | Review and update the ACS URL in the identity provider’s settings | | ``` invalid_assertion_url ``` | The assertion URL in the SAML request is invalid | Verify and update the ACS URL in the identity provider’s settings | | ``` invalid_status ``` | Invalid status | Review and update the SAML configuration settings in the identity provider | | ``` malformed_saml_response ``` | Marshalling error | Ensure SAML response is properly formatted | | ``` assertion_expired ``` | Expired SAML assertion | We received an expired SAML assertion. This could be because of clock skew between the identity provider’s server and our servers. Please reach out to us via your private slack channel or [via email](mailto:support@scalekit.com) | | ``` response_expired ``` | Expired SAML response | We received an expired SAML response. This could be because of clock skew between the identity provider’s server and our servers. Please reach out to us via your private slack channel or [via email](mailto:support@scalekit.com) | | ``` authentication_not_completed ``` | The authentication flow was not completed | Ensure the user completes the login process in the identity provider | | ``` user_login_required ``` | User login is required to continue | Redirect the user to the login page to complete authentication | ## Code exchange errors [Section titled “Code exchange errors”](#code-exchange-errors) These errors come from exchanging the code for the user’s profile, not from the redirect to your callback URL. The SDK throws an error that carries Scalekit’s JSON response, such as `{"error":"invalid_grant","error_description":"invalid code"}`. | Error | Error description | Possible resolution strategy | | ---------------------- | ------------------------------------------ | ---------------------------------------------------------------------------------------------------------- | | ``` invalid_grant ``` | `invalid code` | The code was already used or isn’t valid. Exchange each code once; if an exchange fails, start a new login | | ``` invalid_grant ``` | `redirect_uri does not correspond` | Pass the same redirect URI to the code exchange as to the authorization URL | | ``` invalid_client ``` | `invalid client_id / client_secret` | Use the client ID and secret from the same environment | | ``` invalid_scope ``` | `invalid scope offline_access not allowed` | Remove `offline_access` from the scopes. Modular SSO doesn’t issue refresh tokens |