Try Live
Add Docs
Rankings
Pricing
Enterprise
Docs
Install
Theme
Install
Docs
Pricing
Enterprise
More...
More...
Try Live
Rankings
Create API Key
Add Docs
Scalekit
https://github.com/scalekit-inc/developer-docs
Admin
Scalekit is an enterprise authentication platform offering a complete auth stack for AI apps with
...
Tokens:
1,104
Snippets:
7
Trust Score:
7.5
Update:
1 week ago
Context
Skills
Chat
Benchmark
7.3
Suggestions
Latest
Show doc for...
Code
Info
Show Results
Context Summary (auto-generated)
Raw
Copy
Link
# Scalekit Documentation Scalekit is a complete authentication platform for B2B SaaS applications that provides enterprise-grade authentication capabilities including Single Sign-On (SSO), SCIM directory provisioning, MCP server authorization, and AI agent authentication. The platform handles the complexity of integrating with various identity providers (Okta, Azure AD, Google Workspace) while exposing a unified API and SDKs for Node.js, Python, Go, and Java. The documentation covers five main product areas: Full-Stack Authentication (hosted auth pages with session management), Modular SSO (enterprise SSO integration for existing auth systems), Modular SCIM (directory sync and user provisioning), MCP Auth (OAuth 2.1 authorization for Model Context Protocol servers), and Agent Auth (OAuth token management for AI agents connecting to third-party services). Each module can be used independently or combined to build comprehensive authentication solutions. --- ## SDK Installation and Client Initialization Initialize the Scalekit SDK with your environment credentials to access all authentication APIs. The SDK handles OAuth 2.0 client credentials flow automatically. ```javascript // Node.js import { Scalekit } from '@scalekit-sdk/node'; const scalekit = new Scalekit( process.env.SCALEKIT_ENVIRONMENT_URL, // https://your-org.scalekit.dev process.env.SCALEKIT_CLIENT_ID, process.env.SCALEKIT_CLIENT_SECRET ); ``` ```python # Python from scalekit import ScalekitClient import os scalekit_client = ScalekitClient( env_url=os.getenv("SCALEKIT_ENVIRONMENT_URL"), client_id=os.getenv("SCALEKIT_CLIENT_ID"), client_secret=os.getenv("SCALEKIT_CLIENT_SECRET") ) ``` ```go // Go import "github.com/scalekit-inc/scalekit-sdk-go" scalekitClient := scalekit.NewScalekitClient( os.Getenv("SCALEKIT_ENVIRONMENT_URL"), os.Getenv("SCALEKIT_CLIENT_ID"), os.Getenv("SCALEKIT_CLIENT_SECRET"), ) ``` ```java // Java import com.scalekit.ScalekitClient; ScalekitClient scalekitClient = new ScalekitClient( System.getenv("SCALEKIT_ENVIRONMENT_URL"), System.getenv("SCALEKIT_CLIENT_ID"), System.getenv("SCALEKIT_CLIENT_SECRET") ); ``` --- ## Generate Authorization URL Create an authorization URL to redirect users to Scalekit's hosted authentication page or directly to their enterprise identity provider. Supports SSO routing via organization ID, connection ID, or email domain. ```javascript // Node.js - Full-stack auth with hosted login page const redirectUri = 'https://your-app.com/auth/callback'; const options = { scopes: ['openid', 'profile', 'email', 'offline_access'] }; const authorizationUrl = scalekit.getAuthorizationUrl(redirectUri, options); // Redirect user to: https://<env>.scalekit.dev/oauth/authorize?response_type=code&client_id=skc_xxx&scope=openid%20profile%20email%20offline_access&redirect_uri=... // Node.js - Enterprise SSO with organization routing const ssoOptions = { organizationId: 'org_15421144869927830', // Route to org's SSO // OR connectionId: 'conn_15696105471768821', // Specific SSO connection // OR loginHint: 'user@enterprise.com' // Auto-detect from email domain }; const ssoAuthUrl = scalekit.getAuthorizationUrl(redirectUri, ssoOptions); ``` ```python # Python from scalekit import AuthorizationUrlOptions redirect_uri = 'https://your-app.com/auth/callback' options = AuthorizationUrlOptions() options.scopes = ['openid', 'profile', 'email', 'offline_access'] options.organization_id = 'org_15421144869927830' authorization_url = scalekit_client.get_authorization_url(redirect_uri, options) ``` --- ## Exchange Authorization Code for Tokens After successful authentication, exchange the authorization code for user profile information and session tokens. Returns user details, ID token, access token, and refresh token. ```javascript // Node.js - Express callback handler app.get('/auth/callback', async (req, res) => { const { code, error, error_description } = req.query; if (error) { return res.status(401).json({ error, error_description }); } try { const authResult = await scalekit.authenticateWithCode(code, redirectUri); // authResult contains: // - user: { email, givenName, familyName, id } // - idToken: JWT with user identity claims (sub, oid, email, name) // - accessToken: JWT with roles/permissions // - refreshToken: Long-lived token for session refresh // - expiresIn: Access token expiry in seconds (default 900) const { user, idToken, accessToken, refreshToken } = authResult; // Create session and redirect to dashboard res.cookie('accessToken', accessToken, { httpOnly: true, secure: true }); res.redirect('/dashboard'); } catch (err) { res.status(500).json({ error: 'Authentication failed' }); } }); ``` ```python # Python - FastAPI callback @app.get("/auth/callback") async def callback(code: str = None, error: str = None): if error: raise HTTPException(status_code=401, detail=error) auth_result = scalekit_client.authenticate_with_code(code, redirect_uri) user = auth_result["user"] access_token = auth_result["access_token"] refresh_token = auth_result["refresh_token"] # Store tokens and create session return RedirectResponse(url="/dashboard") ``` --- ## Validate Access Tokens Verify access tokens for protected routes. Validates signature, expiration, issuer, and audience claims. ```javascript // Node.js - Middleware for protected routes const verifyToken = async (req, res, next) => { const accessToken = req.cookies.accessToken; if (!accessToken) { return res.status(401).json({ message: 'No access token' }); } try { const isValid = await scalekit.validateAccessToken(accessToken); if (!isValid) { // Token expired - use refresh token const refreshed = await scalekit.refreshAccessToken(refreshToken); res.cookie('accessToken', refreshed.accessToken, { httpOnly: true }); } next(); } catch (err) { res.status(401).json({ message: 'Invalid token' }); } }; // Apply to protected routes app.get('/dashboard', verifyToken, (req, res) => { res.json({ message: 'Protected content' }); }); ``` ```python # Python - Token validation with claims from scalekit.common.scalekit import TokenValidationOptions options = TokenValidationOptions( issuer="https://your-org.scalekit.dev", audience=["your-resource-id"], required_scopes=["read", "write"] # Optional scope validation ) try: claims = scalekit_client.validate_token(token, options=options) # claims contains: sub, aud, iss, exp, iat, scope, etc. except Exception as e: raise HTTPException(status_code=401, detail="Invalid token") ``` --- ## Refresh Access Tokens Use refresh tokens to obtain new access tokens without requiring user re-authentication. Essential for maintaining long-lived sessions. ```javascript // Node.js try { const refreshed = await scalekit.refreshAccessToken(refreshToken); // refreshed contains: // - user: Updated user profile // - idToken: New ID token // - accessToken: New access token // - refreshToken: New refresh token (rotate it!) // Store new tokens res.cookie('accessToken', refreshed.accessToken, { httpOnly: true, secure: true, maxAge: (refreshed.expiresIn - 60) * 1000 }); } catch (err) { // Refresh token expired - redirect to login res.redirect('/login'); } ``` --- ## Generate Logout URL Create a logout URL to invalidate user sessions on both your app and Scalekit's authorization server. ```javascript // Node.js app.get('/logout', (req, res) => { // Clear local session res.clearCookie('accessToken'); res.clearCookie('refreshToken'); // Generate Scalekit logout URL const logoutUrl = scalekit.getLogoutUrl( idToken, // ID token hint for session identification 'https://your-app.com/logged-out' // Post-logout redirect ); res.redirect(logoutUrl); }); ``` ```python # Python from scalekit.common.scalekit import LogoutUrlOptions options = LogoutUrlOptions( id_token_hint=id_token, post_logout_redirect_uri="https://your-app.com/logged-out" ) logout_url = scalekit_client.get_logout_url(options) ``` --- ## Handle IdP-Initiated SSO Process authentication requests that originate from enterprise identity provider portals. Converts IdP-initiated flows to secure SP-initiated flows. ```javascript // Node.js - Handle login endpoint app.get('/login', async (req, res) => { const { idp_initiated_login, error } = req.query; if (error) { return res.status(400).json({ error }); } if (idp_initiated_login) { // Decode JWT to extract SSO connection details const claims = await scalekit.getIdpInitiatedLoginClaims(idp_initiated_login); const options = { connectionId: claims.connection_id, organizationId: claims.organization_id, loginHint: claims.login_hint, state: claims.relay_state }; // Redirect to complete SP-initiated flow const authUrl = scalekit.getAuthorizationUrl(redirectUri, options); return res.redirect(authUrl); } // Normal login flow res.render('login'); }); ``` --- ## Check SSO Availability by Domain Verify if a domain has an active SSO connection before redirecting users. Prevents failed redirects for users without SSO configured. ```javascript // Node.js const domain = email.split('@')[1].toLowerCase(); const connections = await scalekit.connections.listConnectionsByDomain({ domain }); if (connections.length > 0) { // Domain has SSO - redirect to identity provider const authUrl = scalekit.getAuthorizationUrl(redirectUri, { domainHint: domain }); return res.redirect(authUrl); } else { // No SSO - show password/passwordless login return res.render('password-login'); } ``` --- ## Generate Admin Portal Link Create secure links for enterprise customers to self-configure their SSO connections through Scalekit's Admin Portal. ```javascript // Node.js - Generate shareable link const portalLink = await scalekit.organization.generatePortalLink( 'org_32656XXXXXX0438' // Customer's organization ID ); // Send portalLink.location to customer's IT admin // Example: https://<env>.scalekit.dev/magicLink/8930509d-68cf-4e2c-8c6d-94d2b5e2db43 // Embed in iframe for in-app configuration res.json({ portalUrl: portalLink.location }); ``` ```html <!-- Embed Admin Portal in your settings page --> <iframe src="https://random-subdomain.scalekit.dev/magicLink/8930509d-..." width="100%" height="600" frameborder="0" allow="clipboard-write"> </iframe> ``` --- ## List Directory Users (SCIM) Fetch users from enterprise directory providers (Azure AD, Okta, Google Workspace) for bulk synchronization and provisioning. ```javascript // Node.js const { organizations } = await scalekit.organization.listOrganization({ pageSize: 10 }); const orgId = organizations[0].id; // Get primary directory for organization const { directory } = await scalekit.directory.getPrimaryDirectoryByOrganizationId(orgId); // List all users in directory const { users } = await scalekit.directory.listDirectoryUsers(orgId, directory.id); users.forEach(user => { console.log(`User: ${user.email}, Name: ${user.name}`); // Provision user in your application }); ``` ```python # Python org_list = scalekit_client.organization.list_organizations(page_size=10) org_id = org_list[0].id directory = scalekit_client.directory.get_primary_directory_by_organization_id( organization_id=org_id ) directory_users = scalekit_client.directory.list_directory_users( organization_id=org_id, directory_id=directory.id ) for user in directory_users: print(f"User: {user.email}, Name: {user.name}") ``` --- ## List Directory Groups (SCIM) Retrieve groups from directory providers for role-based access control (RBAC) implementation. ```javascript // Node.js const { groups } = await scalekit.directory.listDirectoryGroups(orgId, directoryId); groups.forEach(group => { console.log(`Group: ${group.name}, ID: ${group.id}`); // Map to application roles }); ``` --- ## Process Directory Webhooks Handle real-time user provisioning events from directory providers. Always verify webhook signatures before processing. ```javascript // Node.js - Express webhook handler app.post('/webhook', async (req, res) => { const event = req.body; const headers = req.headers; const secret = process.env.SCALEKIT_WEBHOOK_SECRET; try { // CRITICAL: Verify webhook signature await scalekit.verifyWebhookPayload(secret, headers, event); } catch (error) { return res.status(400).json({ error: 'Invalid signature' }); } const { email, name } = event.data; switch (event.type) { case 'organization.directory.user_created': await createUserAccount(email, name); break; case 'organization.directory.user_updated': await updateUserAccount(email, name); break; case 'organization.directory.user_deleted': await deactivateUserAccount(email); break; } res.status(201).json({ message: 'Processed' }); }); ``` ```python # Python - FastAPI webhook handler @app.post("/webhook") async def handle_webhook(request: Request): headers = request.headers body = await request.json() # Verify signature is_valid = scalekit_client.verify_webhook_payload( secret=os.getenv("SCALEKIT_WEBHOOK_SECRET"), headers=headers, payload=json.dumps(body).encode('utf-8') ) if not is_valid: raise HTTPException(status_code=400, detail="Invalid signature") event_type = body.get("type") data = body.get("data", {}) if event_type == "organization.directory.user_created": await create_user(data["email"], data["name"]) return {"status": "processed"} ``` --- ## MCP Server OAuth Discovery Endpoint Expose the OAuth protected resource metadata endpoint for MCP clients to discover your authorization server configuration. ```javascript // Node.js - Express app.get('/.well-known/oauth-protected-resource', (req, res) => { res.json({ "authorization_servers": [ "https://<SCALEKIT_ENVIRONMENT_URL>/resources/<YOUR_RESOURCE_ID>" ], "bearer_methods_supported": ["header"], "resource": "https://mcp.yourapp.com", "resource_documentation": "https://mcp.yourapp.com/docs", "scopes_supported": ["todo:read", "todo:write"] }); }); ``` ```python # Python - FastAPI @app.get("/.well-known/oauth-protected-resource") async def get_oauth_protected_resource(): return { "authorization_servers": [ "https://<SCALEKIT_ENVIRONMENT_URL>/resources/<YOUR_RESOURCE_ID>" ], "bearer_methods_supported": ["header"], "resource": "https://mcp.yourapp.com", "scopes_supported": ["todo:read", "todo:write"] } ``` --- ## MCP Server Token Validation Middleware Protect MCP server endpoints by validating Bearer tokens from AI hosts like Claude Desktop, Cursor, or VS Code. ```javascript // Node.js - Complete MCP auth middleware const RESOURCE_ID = 'https://mcp.yourapp.com'; const METADATA_ENDPOINT = 'https://mcp.yourapp.com/.well-known/oauth-protected-resource'; async function authMiddleware(req, res, next) { // Allow public access to discovery endpoint if (req.path.includes('.well-known')) { return next(); } // Extract Bearer token const authHeader = req.headers['authorization']; const token = authHeader?.startsWith('Bearer ') ? authHeader.split('Bearer ')[1]?.trim() : null; if (!token) { return res.status(401) .set('WWW-Authenticate', `Bearer realm="OAuth", resource_metadata="${METADATA_ENDPOINT}"`) .end(); } try { await scalekit.validateToken(token, { issuer: process.env.SCALEKIT_ENVIRONMENT_URL, audience: [RESOURCE_ID] }); next(); } catch (err) { return res.status(401) .set('WWW-Authenticate', `Bearer realm="OAuth", resource_metadata="${METADATA_ENDPOINT}"`) .end(); } } app.use('/', authMiddleware); ``` --- ## Agent Auth: Create Connected Account Register a user's third-party account (Gmail, Slack, etc.) for AI agent tool execution. ```python # Python response = scalekit_client.actions.get_or_create_connected_account( connection_name="gmail", identifier="user_123" # Your system's unique user ID ) connected_account = response.connected_account print(f'Connected account ID: {connected_account.id}') print(f'Status: {connected_account.status}') # ACTIVE, PENDING, etc. ``` ```javascript // Node.js const response = await scalekit.actions.getOrCreateConnectedAccount({ connectionName: 'gmail', identifier: 'user_123' }); const connectedAccount = response.connectedAccount; console.log('Account ID:', connectedAccount?.id); console.log('Status:', connectedAccount?.status); ``` --- ## Agent Auth: Get Authorization Link Generate an OAuth authorization link for users to grant access to third-party services. ```python # Python if connected_account.status != "ACTIVE": link_response = scalekit_client.actions.get_authorization_link( connection_name="gmail", identifier="user_123" ) print(f"Authorization URL: {link_response.link}") # Redirect user to this URL to complete OAuth flow ``` ```javascript // Node.js if (connectedAccount?.status !== ConnectorStatus.ACTIVE) { const linkResponse = await scalekit.actions.getAuthorizationLink({ connectionName: 'gmail', identifier: 'user_123' }); console.log('Auth URL:', linkResponse.link); } ``` --- ## Agent Auth: Execute API Requests via Proxy Call third-party APIs on behalf of users through Scalekit's authenticated proxy. Handles token management automatically. ```python # Python - Fetch Gmail messages result = scalekit_client.actions.request( connection_name="gmail", identifier="user_123", path="/gmail/v1/users/me/messages", method="GET", params={"q": "is:unread", "maxResults": 5} ) print(result) ``` ```javascript // Node.js const result = await scalekit.actions.request({ connectionName: 'gmail', identifier: 'user_123', path: '/gmail/v1/users/me/messages', method: 'GET', queryParams: { q: 'is:unread', maxResults: 5 } }); console.log(result); ``` --- ## Agent Auth: Execute Optimized Tools Use Scalekit's pre-built tools designed for AI agents. Tools abstract API complexity and return structured, AI-friendly responses. ```python # Python response = scalekit_client.actions.execute_tool( tool_name="gmail_fetch_mails", identifier="user_123", tool_input={ "query": "is:unread", "max_results": 5 } ) print(response) ``` ```javascript // Node.js const toolResponse = await scalekit.actions.executeTool({ toolName: 'gmail_fetch_mails', connectedAccountId: connectedAccount?.id, toolInput: { query: 'is:unread', max_results: 5 } }); console.log('Emails:', toolResponse.data); ``` --- ## REST API: Get Access Token Authenticate with the Scalekit API using OAuth 2.0 client credentials flow. ```bash # Get access token curl -X POST "https://<SCALEKIT_ENVIRONMENT_URL>/oauth/token" \ -H "Content-Type: application/x-www-form-urlencoded" \ -d "client_id=${SCALEKIT_CLIENT_ID}" \ -d "client_secret=${SCALEKIT_CLIENT_SECRET}" \ -d "grant_type=client_credentials" # Response: # { # "access_token": "eyJhbGciOiJSUzI1NiI...", # "token_type": "Bearer", # "expires_in": 86399, # "scope": "openid" # } # Use token in API requests curl "https://<SCALEKIT_ENVIRONMENT_URL>/api/v1/organizations?page_size=5" \ -H "Authorization: Bearer ${ACCESS_TOKEN}" ``` --- ## Summary Scalekit provides a comprehensive authentication platform that enables B2B SaaS applications to implement enterprise-grade authentication without building complex identity infrastructure. The main use cases include: adding enterprise SSO to existing applications (Modular SSO), building new applications with hosted authentication (Full-Stack Auth), automating user provisioning from directory providers (Modular SCIM), securing MCP servers for AI tool access (MCP Auth), and enabling AI agents to authenticate with third-party services (Agent Auth). Integration patterns typically follow a standard OAuth 2.0 flow: generate authorization URLs with appropriate routing parameters (organization ID, connection ID, or domain hint), handle the callback to exchange codes for tokens, validate tokens on protected routes, and implement refresh logic for long-lived sessions. For enterprise customers, the Admin Portal provides self-service SSO configuration, while webhooks enable real-time user provisioning. All SDKs (Node.js, Python, Go, Java) follow consistent naming conventions and API patterns, making it straightforward to implement authentication across different technology stacks.