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)  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.  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