### Create Organization Example
Source: https://github.com/workos/workos-ruby/blob/main/_autodocs/api-reference/organizations.md
Provides a practical example of creating an organization with a name, domains, and metadata. This is useful for quick setup or testing.
```ruby
org = client.organizations.create_organization(
name: "Engineering Team",
domains: ["eng.company.com"],
metadata: {
"team" => "platform",
"cost_center" => "engineering"
}
)
puts org.id # => "org_123..."
puts org.name # => "Engineering Team"
puts org.domains # => ["eng.company.com"]
puts org.metadata["team"] # => "platform"
```
--------------------------------
### CLI Authentication with PKCE
Source: https://github.com/workos/workos-ruby/blob/main/_autodocs/api-reference/public-client.md
This example demonstrates how to implement a CLI application that uses the WorkOS Public Client to authenticate users via a browser flow with PKCE. It starts a local server to handle the OAuth callback and exchanges the authorization code for tokens.
```ruby
#!/usr/bin/env ruby
# workos-cli.rb
require "workos"
require "webrick"
class WorkOSCLIAuth
def self.login
client_id = ENV.fetch("WORKOS_CLIENT_ID")
public_client = WorkOS::PublicClient.create(client_id: client_id)
# Generate PKCE authorization URL
url, verifier, state = public_client.user_management.get_authorization_url_with_pkce(
redirect_uri: "http://localhost:3000/callback"
)
puts "Opening browser for authentication..."
system("open", url)
# Start local server to handle callback
server = WEBrick::HTTPServer.new(Port: 3000)
auth_code = nil
server.mount_proc "/callback" do |req|
code = req.query_string.match(/code=([^&]+)/)[1]
# Exchange code for tokens
result = public_client.user_management.create_authenticate(
client_id: client_id,
grant_type: "authorization_code",
code: code,
code_verifier: verifier
)
auth_code = code
req.response.body = "Authentication successful! You can close this window."
server.shutdown
end
server.start
return auth_code
end
end
# Usage
code = WorkOSCLIAuth.login
```
--------------------------------
### Directory Sync Intent Example
Source: https://github.com/workos/workos-ruby/blob/main/_autodocs/api-reference/admin-portal.md
Example of generating a link for the Directory Sync intent.
```APIDOC
### Directory Sync Intent
```ruby
response = client.admin_portal.generate_link(
organization: "org_123",
intent: "dsync"
)
```
```
--------------------------------
### Get Organization Example
Source: https://github.com/workos/workos-ruby/blob/main/_autodocs/api-reference/organizations.md
Demonstrates retrieving an organization by its ID and accessing its name and response details like HTTP status and request ID. Useful for verifying retrieval and debugging.
```ruby
org = client.organizations.get_organization(id: "org_123")
puts org.name
puts org.last_response.http_status # => 200
puts org.last_response.request_id # => "req_..."
```
--------------------------------
### Example: Create and Inspect New SAML Connection
Source: https://github.com/workos/workos-ruby/blob/main/_autodocs/api-reference/sso.md
Shows how to create a new SAML connection for an organization and then print its ID and initial state.
```ruby
connection = client.sso.create_connection(
name: "Acme SAML",
connection_type: "SAML",
organization_id: "org_123",
domain: "acme.com"
)
puts connection.id # => "conn_..."
puts connection.state # => "needs_setup"
```
--------------------------------
### Get Organization by External ID Example
Source: https://github.com/workos/workos-ruby/blob/main/_autodocs/api-reference/organizations.md
Provides an example of retrieving an organization by its external ID. This is helpful for testing or when you only have the external identifier available.
```ruby
org = client.organizations.get_organization_by_external_id(
external_id: "customer_12345"
)
```
--------------------------------
### Example: List SAML Connections and Iterate
Source: https://github.com/workos/workos-ruby/blob/main/_autodocs/api-reference/sso.md
Demonstrates how to list SAML connections for a specific organization with a limit and then iterate through the results to display connection details.
```ruby
# List SAML connections for an organization
connections = client.sso.list_connections(
organization_id: "org_123",
connection_type: "SAML",
limit: 50
)
connections.auto_paging_each do |conn|
puts "#{conn.id}: #{conn.name} (#{conn.connection_type})"
puts "Domain: #{conn.domain}"
puts "Status: #{conn.state}"
end
```
--------------------------------
### Initialize WorkOS Client
Source: https://github.com/workos/workos-ruby/blob/main/_autodocs/api-reference/client.md
Instantiate the WorkOS client with specific configuration parameters. Useful for custom setups or when not using the global configuration.
```ruby
client = WorkOS::Client.new(
api_key: "sk_test_...",
client_id: "client_...",
base_url: "https://api.workos.com",
timeout: 30,
max_retries: 2,
logger: nil,
log_level: nil
)
```
--------------------------------
### Setup SAML Connection for Organization
Source: https://github.com/workos/workos-ruby/blob/main/_autodocs/api-reference/sso.md
Create a new SAML connection for an organization, retrieve its SAML metadata, and then activate the connection. Ensure the organization ID and domain are correctly specified.
```ruby
connection = client.sso.create_connection(
name: "Acme SAML",
connection_type: "SAML",
organization_id: "org_123",
domain: "acme.com"
)
saml_metadata = connection.saml_metadata
puts "SAML Metadata:"
puts saml_metadata
connection = client.sso.activate_connection(id: connection.id)
puts "Connection state: #{connection.state}" # => "active"
```
--------------------------------
### Configure and Get Global WorkOS Client
Source: https://github.com/workos/workos-ruby/blob/main/_autodocs/api-reference/client.md
Configure the global WorkOS client using a block and then retrieve the singleton instance. This is the recommended approach for most applications.
```ruby
WorkOS.configure do |config|
config.api_key = ENV.fetch("WORKOS_API_KEY")
config.client_id = ENV["WORKOS_CLIENT_ID"]
config.timeout = 60
config.logger = Logger.new($stdout)
config.log_level = :info
end
client = WorkOS.client
```
--------------------------------
### Install WorkOS Gem
Source: https://github.com/workos/workos-ruby/blob/main/README.md
Install the WorkOS gem using the gem command. Ensure you are using a Ruby version compatible with the gem.
```sh
gem install workos
```
--------------------------------
### Audit Logs Intent Example
Source: https://github.com/workos/workos-ruby/blob/main/_autodocs/api-reference/admin-portal.md
Example of generating a link for the Audit Logs intent.
```APIDOC
### Audit Logs Intent
```ruby
response = client.admin_portal.generate_link(
organization: "org_123",
intent: "audit_logs"
)
```
```
--------------------------------
### Admin Portal for Different Intents
Source: https://github.com/workos/workos-ruby/blob/main/_autodocs/api-reference/admin-portal.md
Example of dynamically generating an Admin Portal link based on a provided intent parameter.
```APIDOC
### Admin Portal for Different Intents
```ruby
class AdminPortalController < ApplicationController
def show
intent = params[:intent] || "sso"
@portal_link = WorkOS.client.admin_portal.generate_link(
organization: current_org.workos_id,
intent: intent,
return_url: admin_portal_path,
success_url: admin_portal_success_path
)
redirect_to @portal_link.link
end
def success
flash[:notice] = "Configuration completed successfully"
redirect_to dashboard_path
end
end
# routes
get "/admin/portal/:intent", to: "admin_portal#show"
get "/admin/portal/success", to: "admin_portal#success"
```
```
--------------------------------
### Create User with Organization ID
Source: https://github.com/workos/workos-ruby/blob/main/_autodocs/api-reference/user-management.md
Example of creating a user associated with a specific organization, including first name, last name, and a plaintext password.
```ruby
user = client.user_management.create_user(
email: "alice@company.com",
first_name: "Alice",
last_name: "Smith",
organization_id: "org_123",
password: WorkOS::UserManagement::PasswordPlaintext.new(
password: "SecurePassword123!"
)
)
puts user.id # => "user_..."
puts user.email # => "alice@company.com"
```
--------------------------------
### Install WorkOS Gem
Source: https://github.com/workos/workos-ruby/blob/main/_autodocs/README.md
Add the WorkOS gem to your application's Gemfile to begin using the SDK.
```ruby
gem "workos"
```
--------------------------------
### Admin Portal Link for Different Intents
Source: https://github.com/workos/workos-ruby/blob/main/_autodocs/api-reference/admin-portal.md
This example demonstrates how to dynamically generate an Admin Portal link based on a provided intent parameter. It includes controller logic and corresponding routes for handling different intents.
```ruby
class AdminPortalController < ApplicationController
def show
intent = params[:intent] || "sso"
@portal_link = WorkOS.client.admin_portal.generate_link(
organization: current_org.workos_id,
intent: intent,
return_url: admin_portal_path,
success_url: admin_portal_success_path
)
redirect_to @portal_link.link
end
def success
flash[:notice] = "Configuration completed successfully"
redirect_to dashboard_path
end
end
# routes
get "/admin/portal/:intent", to: "admin_portal#show"
get "/admin/portal/success", to: "admin_portal#success"
```
--------------------------------
### Rails Webhook Integration Example
Source: https://github.com/workos/workos-ruby/blob/main/_autodocs/api-reference/webhooks.md
Configure routes, controllers, and models in a Rails application to receive and process WorkOS webhook events. This example demonstrates signature verification and event handling for user and organization data.
```ruby
# config/routes.rb
post "/webhooks/workos", to: "webhooks#workos"
# app/controllers/webhooks_controller.rb
class WebhooksController < ApplicationController
skip_before_action :verify_authenticity_token, only: [:workos]
def workos
event = WorkOS.client.webhooks.construct_event(
payload: request.body.read,
sig_header: request.headers["WorkOS-Signature"],
secret: ENV.fetch("WORKOS_WEBHOOK_SECRET")
)
case event.event
when "user.created"
User.create_from_webhook(event.data["user"], event.data["organization_id"])
when "user.updated"
user = User.find_by(workos_id: event.data["user"]["id"])
user&.update_from_webhook(event.data["user"])
when "organization.created"
Organization.create_from_webhook(event.data["organization"])
end
head :ok
rescue WorkOS::SignatureVerificationError
head :unauthorized
rescue => e
Rails.logger.error("Webhook error: #{e.message}")
head :internal_server_error
end
end
# app/models/user.rb
class User < ApplicationRecord
def self.create_from_webhook(data, organization_id)
create!(
workos_id: data["id"],
email: data["email"],
first_name: data["first_name"],
last_name: data["last_name"],
organization_id: organization_id
)
end
def update_from_webhook(data)
update(
email: data["email"],
first_name: data["first_name"],
last_name: data["last_name"]
)
end
end
```
--------------------------------
### Paginate Organizations with Cursor Tracking
Source: https://github.com/workos/workos-ruby/blob/main/_autodocs/api-reference/organizations.md
Iterate through organizations using cursor-based pagination. This example fetches organizations in batches of 50 and continues fetching until no more results are available.
```ruby
organizations = client.organizations.list_organizations(limit: 50)
loop do
organizations.data.each { |org| puts org.name }
break unless organizations.list_metadata.after
organizations = client.organizations.list_organizations(
after: organizations.list_metadata.after,
limit: 50
)
end
```
--------------------------------
### MFA Setup Flow (SMS or TOTP)
Source: https://github.com/workos/workos-ruby/blob/main/_autodocs/api-reference/multi-factor-auth.md
Initiates the MFA enrollment process, handling both SMS and TOTP factor types. Stores the factor ID in the session for subsequent verification. Requires user ID, and for SMS, a phone number; for TOTP, issuer and user identifier.
```ruby
def setup_mfa
# User chooses MFA type
type = params[:type] # "sms" or "totp"
if type == "sms"
# SMS enrollment
factor = client.multi_factor_auth.enroll_factor(
type: "sms",
phone_number: params[:phone],
user_id: current_user.workos_id
)
@message = "SMS code sent to #{params[:phone]}"
@verify_url = verify_mfa_path(factor_id: factor.id)
else
# TOTP enrollment
factor = client.multi_factor_auth.enroll_factor(
type: "totp",
totp_issuer: "My App",
totp_user: current_user.email,
user_id: current_user.workos_id
)
@qr_code = factor.totp_qr_code
@secret = factor.totp_secret
@verify_url = verify_mfa_path(factor_id: factor.id)
end
session[:mfa_factor_id] = factor.id
render :mfa_setup
end
def verify_mfa_setup
factor_id = session[:mfa_factor_id]
code = params[:code]
result = client.multi_factor_auth.verify_challenge(
id: factor_id,
code: code
)
if result.valid
current_user.update(
mfa_factor_id: factor_id,
mfa_verified: true
)
flash[:notice] = "MFA enabled successfully"
redirect_to account_settings_path
else
flash[:error] = "Invalid code. Please try again."
redirect_to setup_mfa_path
end
end
```
--------------------------------
### Generate Directory Sync Intent Link
Source: https://github.com/workos/workos-ruby/blob/main/_autodocs/api-reference/admin-portal.md
Generates a link to the Admin Portal pre-configured for Directory Sync setup.
```ruby
response = client.admin_portal.generate_link(
organization: "org_123",
intent: "dsync"
)
```
--------------------------------
### SSO Intent Options
Source: https://github.com/workos/workos-ruby/blob/main/_autodocs/api-reference/admin-portal.md
Example of configuring the SSO intent to restrict visible connection types.
```APIDOC
### SSO Intent
```ruby
response = client.admin_portal.generate_link(
organization: "org_123",
intent: "sso",
intent_options: {
"connection_types" => ["SAML", "Google"]
}
)
```
```
--------------------------------
### TOTP-Based MFA Workflow
Source: https://github.com/workos/workos-ruby/blob/main/_autodocs/api-reference/multi-factor-auth.md
This snippet illustrates the process of enrolling a user in TOTP-based MFA, displaying a QR code for authenticator app setup, and verifying the TOTP code.
```APIDOC
## TOTP-Based MFA
### Description
This workflow guides through enrolling a user in TOTP MFA, providing a QR code for authenticator apps, and verifying the TOTP code.
### Steps
1. **Enroll user in TOTP MFA**
```ruby
factor = client.multi_factor_auth.enroll_factor(
type: "totp",
totp_issuer: "My App",
totp_user: user.email,
user_id: user_id
)
```
2. **Display QR code to user**
*User scans the QR code with an authenticator app or enters the secret manually.*
```ruby
qr_code_url = factor.totp_qr_code
```
3. **Verify TOTP code**
```ruby
result = client.multi_factor_auth.verify_challenge(
id: factor.id,
code: params[:totp_code]
)
if result.valid
user.update(mfa_verified: true)
else
render :mfa_verification, error: "Invalid code"
end
```
### Data Models
- `WorkOS::AuthenticationFactorEnrolled`: Represents a newly enrolled MFA factor.
- `WorkOS::AuthenticationChallengeVerifyResponse`: Represents the result of an MFA challenge verification.
```
--------------------------------
### Embed Admin Portal Link in Dashboard
Source: https://github.com/workos/workos-ruby/blob/main/_autodocs/api-reference/admin-portal.md
This example shows how to generate an Admin Portal link for SSO configuration and embed it within a dashboard. The `return_url` and `success_url` parameters define where the user is redirected after completing or canceling the configuration.
```ruby
class OrganizationController < ApplicationController
def sso_settings
@org = current_organization
@portal_link = WorkOS.client.admin_portal.generate_link(
organization: @org.workos_id,
intent: "sso",
return_url: org_path(@org),
success_url: org_path(@org, anchor: "sso-configured")
)
end
end
# view
Configure SSO
```
--------------------------------
### Generate Admin Portal Link
Source: https://github.com/workos/workos-ruby/blob/main/_autodocs/README.md
Generates a link to the WorkOS Admin Portal for SSO setup.
```ruby
client.admin_portal.generate_link(intent: "sso")
```
--------------------------------
### IT Contact Notifications
Source: https://github.com/workos/workos-ruby/blob/main/_autodocs/api-reference/admin-portal.md
Example of using `it_contact_emails` to grant multiple admin/IT contacts access to the portal and notify them.
```APIDOC
### IT Contact Notifications
```ruby
# Grant multiple admin/IT contacts access to the portal
response = client.admin_portal.generate_link(
organization: org_id,
intent: "sso",
it_contact_emails: [
"admin1@company.com",
"admin2@company.com",
"it-team@company.com"
]
)
# Each contact will receive a notification about portal access
```
```
--------------------------------
### WorkOS Ruby SDK Project Structure
Source: https://github.com/workos/workos-ruby/blob/main/_autodocs/IMPLEMENTATION_SUMMARY.md
This snippet illustrates the organized directory structure of the WorkOS Ruby SDK, showing the entry point, navigation guides, and the breakdown of API reference documentation by service.
```plaintext
/workspace/home/output/
├── README.md (Entry point + quick reference)
├── REFERENCE_MAP.md (Navigation guide + coverage)
├── overview.md (Architecture)
├── configuration.md (Config + best practices)
├── errors.md (Error handling)
├── types.md (Data types)
└── api-reference/ (10 service modules)
├── client.md
├── user-management.md
├── sso.md
├── session-manager.md
├── organizations.md
├── webhooks.md
├── multi-factor-auth.md
├── admin-portal.md
├── public-client.md
└── directory-sync.md
```
--------------------------------
### Example Redacted Log Output
Source: https://github.com/workos/workos-ruby/blob/main/_autodocs/configuration.md
Observe how sensitive data like path tokens and query parameters are automatically redacted in log output.
```text
request start method=GET path=/user_management/invitations/by_token/[REDACTED] attempt=1
request error method=POST path=/organizations/org_123?code=[REDACTED] status=400 request_id=req_123
```
--------------------------------
### Get Organization with Per-Request Options (Ruby)
Source: https://github.com/workos/workos-ruby/blob/main/README.md
Demonstrates how to override default request options like timeout, extra headers, and idempotency keys for a specific API call.
```ruby
organization = WorkOS.client.organizations.get_organization(
id: "org_123",
request_options: {
timeout: 10,
extra_headers: {"X-Request-Source" => "admin"},
idempotency_key: "org-create-123"
}
)
```
--------------------------------
### User Signup with Invitation
Source: https://github.com/workos/workos-ruby/blob/main/_autodocs/api-reference/user-management.md
This workflow demonstrates creating a user and then sending them an invitation. Ensure you have the `client` object initialized and `current_org` and `params` available.
```ruby
# Create user
user = client.user_management.create_user(
email: params[:email],
first_name: params[:first_name],
organization_id: current_org.id
)
# Send invitation
invitation = client.user_management.create_user_invitation(
email: user.email,
organization_id: current_org.id,
expires_in_days: 14
)
```
--------------------------------
### Get WorkOS Ruby SDK Version
Source: https://github.com/workos/workos-ruby/blob/main/_autodocs/README.md
Use this snippet to display the current version of the WorkOS Ruby SDK. Ensure the SDK is installed.
```ruby
puts WorkOS::VERSION # Current version
```
--------------------------------
### Client Initialization
Source: https://github.com/workos/workos-ruby/blob/main/_autodocs/api-reference/client.md
Instantiate the WorkOS client with various configuration options.
```APIDOC
## WorkOS::Client.new
### Description
Initializes a new WorkOS client instance with specified configuration parameters.
### Parameters
#### Path Parameters
None
#### Query Parameters
None
#### Request Body
None
### Parameters Table
| Parameter | Type | Required | Default | Description |
|-----------|------|----------|---------|-------------|
| `api_key` | String | No | None | WorkOS API key for Bearer authentication |
| `client_id` | String | No | None | WorkOS Client ID for OAuth flows |
| `base_url` | String | No | `https://api.workos.com` | API endpoint base URL |
| `timeout` | Integer | No | 30 | Request timeout in seconds |
| `max_retries` | Integer | No | 2 | Maximum retry attempts for transient failures |
| `logger` | Logger | No | None | Logger instance (any object responding to `debug`, `info`, `warn`, `error`, or `add`) |
| `log_level` | Symbol | No | None | Minimum log level (`:debug`, `:info`, `:warn`, `:error`, `:unknown`) |
### Request Example
```ruby
client = WorkOS::Client.new(
api_key: "sk_test_...",
client_id: "client_...",
base_url: "https://api.workos.com",
timeout: 30,
max_retries: 2,
logger: nil,
log_level: nil
)
```
### Response
#### Success Response (200)
An initialized `WorkOS::Client` object.
#### Response Example
(No specific response example provided, but an instance of `WorkOS::Client` is returned.)
```
--------------------------------
### Get Single Directory User
Source: https://github.com/workos/workos-ruby/blob/main/_autodocs/api-reference/directory-sync.md
Fetches a single directory user by their ID. This is used to get detailed information about a specific user.
```ruby
user = client.directory_sync.get_user(
id: "user_123",
request_options: {}
)
```
--------------------------------
### Create a User (Ruby)
Source: https://github.com/workos/workos-ruby/blob/main/README.md
Creates a new user with provided email, first name, and last name, then prints the new user's ID.
```ruby
user = WorkOS.client.user_management.create_user(
email: "marceline@example.com",
first_name: "Marceline",
last_name: "Abadeer"
)
puts user.id
```
--------------------------------
### Create a Public Client Instance
Source: https://github.com/workos/workos-ruby/blob/main/_autodocs/api-reference/public-client.md
Use the `create` factory method to instantiate a public client. Provide your WorkOS Client ID. Optional parameters include `base_url`, `timeout`, `max_retries`, `logger`, and `log_level`.
```ruby
client = WorkOS::PublicClient.create(
client_id: "client_123",
base_url: nil,
timeout: nil,
max_retries: nil,
logger: nil,
log_level: nil
)
```
```ruby
# Browser-based SPA
public_client = WorkOS::PublicClient.create(client_id: "client_123")
```
```ruby
# With logging
public_client = WorkOS::PublicClient.create(
client_id: "client_123",
logger: Rails.logger,
log_level: :info
)
```
--------------------------------
### Get Organization
Source: https://github.com/workos/workos-ruby/blob/main/README.md
Retrieves a specific organization by its ID.
```APIDOC
## Get Organization
### Description
Retrieves a specific organization by its ID.
### Method
`get_organization`
### Parameters
#### Path Parameters
- **id** (String) - Required - The unique identifier of the organization.
#### Query Parameters
- **request_options** (Hash) - Optional - Per-request options like timeout, extra headers, and idempotency key.
- **timeout** (Integer) - Optional - Request timeout in seconds.
- **extra_headers** (Hash) - Optional - Additional headers to send with the request.
- **idempotency_key** (String) - Optional - An idempotency key for the request.
### Request Example
```ruby
organization = WorkOS.client.organizations.get_organization(id: "org_123")
puts organization.name
```
### Response
#### Success Response (200)
- **id** (String) - The unique identifier of the organization.
- **name** (String) - The name of the organization.
```
--------------------------------
### Get Directory User
Source: https://github.com/workos/workos-ruby/blob/main/_autodocs/api-reference/directory-sync.md
Retrieves a specific user from a directory by their ID.
```APIDOC
## get_user
### Description
Retrieves a specific user from a directory by their ID.
### Method
`client.directory_sync.get_user`
### Parameters
#### Query Parameters
- **id** (string) - Required - The ID of the user to retrieve.
### Request Example
```ruby
ds_user = client.directory_sync.get_user(id: user_id)
puts ds_user.email
```
### Response
#### Success Response
Returns a `WorkOS::DirectoryUser` object.
#### Response Example
```json
{
"id": "user_123",
"first_name": "Jane",
"last_name": "Doe",
"email": "jane.doe@example.com",
"username": "jane.doe",
"state": "active",
"directory_id": "dir_abc",
"raw_attributes": {},
"created_at": "2023-01-01T12:00:00Z",
"updated_at": "2023-01-01T12:00:00Z"
}
```
```
--------------------------------
### Get Organization by External ID
Source: https://github.com/workos/workos-ruby/blob/main/_autodocs/api-reference/organizations.md
Retrieves an organization using its external identifier.
```APIDOC
## get_organization_by_external_id
### Description
Retrieve an organization by its external ID.
### Method
`get_organization_by_external_id`
### Parameters
#### Query Parameters
- **external_id** (String) - Required - External ID
- **request_options** (Hash) - Optional - Per-request overrides - Default: {}
### Response
#### Success Response
- Returns `WorkOS::Organization`
#### Error Handling
- `WorkOS::NotFoundError` if not found
### Request Example
```ruby
org = client.organizations.get_organization_by_external_id(
external_id: "acme_001",
request_options: {}
)
```
### Response Example
```ruby
org = client.organizations.get_organization_by_external_id(
external_id: "customer_12345"
)
```
```
--------------------------------
### Singleton Client Configuration (Recommended)
Source: https://github.com/workos/workos-ruby/blob/main/_autodocs/configuration.md
Configure the WorkOS SDK globally using `WorkOS.configure` for simple, single-tenant applications. This sets the API key and client ID for all subsequent client interactions.
```ruby
WorkOS.configure do |config|
config.api_key = ENV.fetch("WORKOS_API_KEY")
config.client_id = ENV["WORKOS_CLIENT_ID"]
end
# Throughout your application
WorkOS.client.organizations.list_organizations
```
--------------------------------
### Singleton Client Configuration
Source: https://github.com/workos/workos-ruby/blob/main/README.md
Configure the WorkOS SDK using the singleton pattern, recommended for most applications. This sets up a single client instance for your application. Then, call methods on the WorkOS.client object.
```ruby
WorkOS.configure do |config|
config.api_key = ENV.fetch("WORKOS_API_KEY")
config.client_id = ENV["WORKOS_CLIENT_ID"]
end
WorkOS.client.organizations.list_organizations
```
--------------------------------
### Get Authorization URL
Source: https://github.com/workos/workos-ruby/blob/main/_autodocs/README.md
Generates the URL for initiating OAuth authentication flow.
```ruby
client.user_management.get_authorization_url
```
--------------------------------
### Get Webhook Endpoint
Source: https://github.com/workos/workos-ruby/blob/main/_autodocs/api-reference/webhooks.md
Retrieves a specific webhook endpoint by its unique ID.
```APIDOC
## get_webhook_endpoint
### Description
Retrieve a webhook endpoint by ID.
### Method
`get_webhook_endpoint`
### Parameters
#### Path Parameters
- **id** (String) - Required - Webhook endpoint ID
#### Query Parameters
- **request_options** (Hash) - Optional - Per-request overrides - Default: {}
### Returns
`WorkOS::WebhookEndpoint`
### Throws
`WorkOS::NotFoundError`
### Request Example
```ruby
endpoint = client.webhooks.get_webhook_endpoint(
id: "we_...",
request_options: {}
)
```
```
--------------------------------
### Session Management with Public Client
Source: https://github.com/workos/workos-ruby/blob/main/_autodocs/api-reference/public-client.md
Shows how to initialize and use the session manager with a public client. This involves loading a session using provided cookie data and a password, and then authenticating the session.
```ruby
# ✅ Session operations work
manager = public_client.session_manager
session = manager.load(seal_data: cookie, cookie_password: password)
result = session.authenticate
```
--------------------------------
### Get SSO Connection
Source: https://github.com/workos/workos-ruby/blob/main/_autodocs/api-reference/sso.md
Retrieves a specific SSO connection by its unique identifier.
```APIDOC
## get_connection
### Description
Retrieve a single connection by ID.
### Method
`get_connection`
### Parameters
#### Query Parameters
- **id** (String) - Required - Connection ID
- **request_options** (Hash) - Optional - Per-request overrides
### Returns
`WorkOS::Connection`
### Throws
`WorkOS::NotFoundError`
```
--------------------------------
### Global Client Configuration
Source: https://github.com/workos/workos-ruby/blob/main/_autodocs/api-reference/client.md
Configure the singleton global client using `WorkOS.configure`.
```APIDOC
## WorkOS.client
### Description
Returns the singleton global client instance, configured via `WorkOS.configure`.
### Method
`WorkOS.client`
### Parameters
None
### Request Example
```ruby
WorkOS.configure do |config|
config.api_key = ENV.fetch("WORKOS_API_KEY")
config.client_id = ENV["WORKOS_CLIENT_ID"]
config.timeout = 60
config.logger = Logger.new($stdout)
config.log_level = :info
end
client = WorkOS.client
```
### Response
#### Success Response (200)
The globally configured `WorkOS::Client` instance.
#### Response Example
(No specific response example provided, but an instance of `WorkOS::Client` is returned.)
```
--------------------------------
### Get Authorization URL
Source: https://github.com/workos/workos-ruby/blob/main/_autodocs/api-reference/user-management.md
Generates a URL to redirect users to for authentication via OAuth.
```APIDOC
## GET /authorize
### Description
Generates an authorization URL for OAuth flow.
### Method
GET
### Endpoint
/authorize
### Parameters
#### Query Parameters
- **client_id** (string) - Required - Your WorkOS client ID.
- **redirect_uri** (string) - Required - The URI to redirect to after authentication.
- **state** (string) - Optional - An opaque value used to maintain state between the request and callback.
### Response
#### Success Response (200)
- **url** (string) - The authorization URL.
### Response Example
```json
{
"url": "https://auth.workos.com/authorize?client_id=..."
}
```
```
--------------------------------
### Get Factor
Source: https://github.com/workos/workos-ruby/blob/main/_autodocs/api-reference/multi-factor-auth.md
Retrieves details of a specific MFA factor using its unique ID.
```APIDOC
## get_factor
### Description
Retrieve a factor by ID.
### Method
`client.multi_factor_auth.get_factor`
### Parameters
#### Path Parameters
None
#### Query Parameters
None
#### Request Body
None
#### Parameters
- **id** (String) - Required - Factor ID
- **request_options** (Hash) - Optional - Per-request overrides
### Request Example
```ruby
factor = client.multi_factor_auth.get_factor(
id: "factor_123",
request_options: {}
)
```
### Response
#### Success Response
`WorkOS::AuthenticationFactor` object representing the requested factor.
### Error Handling
- `WorkOS::NotFoundError`: Thrown if the factor with the specified ID is not found.
```
--------------------------------
### Handle User Provisioning Event
Source: https://github.com/workos/workos-ruby/blob/main/_autodocs/api-reference/directory-sync.md
Handles the `directory_user.created` webhook event by fetching the user details and creating a corresponding user in your application.
```ruby
# Webhook handler for directory_user.created event
def handle_user_created(data)
ds_user_id = data["directory_user"]["id"]
ds_user = client.directory_sync.get_user(id: ds_user_id)
# Create application user
user = User.create!(
workos_id: ds_user.id,
email: ds_user.email,
first_name: ds_user.first_name,
last_name: ds_user.last_name,
organization_id: org_id
)
end
```
--------------------------------
### Manual Pagination for Organizations
Source: https://github.com/workos/workos-ruby/blob/main/_autodocs/api-reference/organizations.md
Illustrates manual pagination by fetching the first page and then the subsequent page using the `after` cursor. This provides fine-grained control over fetching data in chunks.
```ruby
# Manual pagination
first_page = client.organizations.list_organizations(limit: 50)
if first_page.list_metadata.after
second_page = client.organizations.list_organizations(after: first_page.list_metadata.after, limit: 50)
end
```
--------------------------------
### Get a Single Organization (Ruby)
Source: https://github.com/workos/workos-ruby/blob/main/README.md
Retrieves a specific organization by its ID and prints its name.
```ruby
organization = WorkOS.client.organizations.get_organization(id: "org_123")
puts organization.name
```
--------------------------------
### Configure SDK Logging
Source: https://github.com/workos/workos-ruby/blob/main/_autodocs/configuration.md
Set up a custom logger and configure the SDK's logging level. Ensure you have the 'logger' gem required.
```ruby
require "logger"
logger = Logger.new("workos.log")
logger.level = Logger::DEBUG
WorkOS.configure do |config|
config.api_key = ENV.fetch("WORKOS_API_KEY")
config.logger = logger
config.log_level = :debug
end
```
--------------------------------
### Multi-tenant Client Initialization
Source: https://github.com/workos/workos-ruby/blob/main/README.md
Initialize multiple WorkOS clients for multi-tenant applications, where each tenant has a unique API key. This allows for isolated client instances per tenant.
```ruby
tenant_a = WorkOS::Client.new(api_key: "sk_tenant_a", client_id: "client_a")
tenant_b = WorkOS::Client.new(api_key: "sk_tenant_b", client_id: "client_b")
tenant_a.organizations.list_organizations
tenant_b.organizations.list_organizations
```
--------------------------------
### Get Authorization URL with PKCE
Source: https://github.com/workos/workos-ruby/blob/main/_autodocs/api-reference/user-management.md
Generates an authorization URL for OAuth with PKCE, suitable for browser and mobile applications.
```APIDOC
## GET /authorize
### Description
Generates an authorization URL with PKCE for OAuth flow.
### Method
GET
### Endpoint
/authorize
### Parameters
#### Query Parameters
- **client_id** (string) - Required - Your WorkOS client ID.
- **redirect_uri** (string) - Required - The URI to redirect to after authentication.
- **code_challenge** (string) - Required - The code challenge generated from the code verifier.
- **code_challenge_method** (string) - Required - The method used to generate the code challenge (e.g., "S256").
- **state** (string) - Optional - An opaque value used to maintain state between the request and callback.
### Response
#### Success Response (200)
- **url** (string) - The authorization URL.
### Response Example
```json
{
"url": "https://auth.workos.com/authorize?client_id=...&code_challenge=...&code_challenge_method=S256"
}
```
```
--------------------------------
### Configure WorkOS SDK Globally
Source: https://github.com/workos/workos-ruby/blob/main/_autodocs/configuration.md
Configure the SDK globally using `WorkOS.configure`. Set your API key, client ID, and other options. The client can then be accessed via `WorkOS.client`.
```ruby
WorkOS.configure do |config|
config.api_key = ENV.fetch("WORKOS_API_KEY")
config.client_id = ENV["WORKOS_CLIENT_ID"]
config.base_url = "https://api.workos.com"
config.timeout = 30
config.max_retries = 2
config.logger = Logger.new($stdout)
config.log_level = :info
end
client = WorkOS.client
```
--------------------------------
### Create User with Metadata
Source: https://github.com/workos/workos-ruby/blob/main/_autodocs/types.md
Use this to create a user and attach custom metadata. Metadata is stored as a Hash of String keys and String values.
```ruby
user = client.user_management.create_user(
email: "user@example.com",
metadata: {
"customer_id" => "stripe_123",
"team" => "engineering"
}
)
puts user.metadata["customer_id"] # => "stripe_123"
```
--------------------------------
### Embed Portal Link in Dashboard
Source: https://github.com/workos/workos-ruby/blob/main/_autodocs/api-reference/admin-portal.md
Example of embedding an Admin Portal link within a dashboard, specifically for SSO configuration.
```APIDOC
## Example Workflows
### Embed Portal Link in Dashboard
```ruby
class OrganizationController < ApplicationController
def sso_settings
@org = current_organization
@portal_link = WorkOS.client.admin_portal.generate_link(
organization: @org.workos_id,
intent: "sso",
return_url: org_path(@org),
success_url: org_path(@org, anchor: "sso-configured")
)
end
end
# view
Configure SSO
```
```
--------------------------------
### Get Audit Log Configuration
Source: https://github.com/workos/workos-ruby/blob/main/_autodocs/api-reference/organizations.md
Retrieve the audit log configuration for a given organization. This includes details about log streams.
```ruby
config = client.organizations.get_audit_log_configuration(
id: "org_123",
request_options: {}
)
```
```ruby
config = client.organizations.get_audit_log_configuration(id: "org_123")
puts config.organization_id
puts config.streams # Array of log stream configs
```
--------------------------------
### Create Organization
Source: https://github.com/workos/workos-ruby/blob/main/_autodocs/api-reference/organizations.md
Creates a new organization with a name and optional details like domains, domain data, metadata, and an external ID. Use this when setting up new business units or workspaces.
```ruby
org = client.organizations.create_organization(
name: "Acme Corp",
allow_profiles_outside_organization: false,
domains: ["acme.com"],
domain_data: [
{domain: "acme.com", verification_state: "verified"}
],
metadata: {"billing_id" => "stripe_123"},
external_id: "acme_001",
request_options: {}
)
```
--------------------------------
### Get Organization by ID
Source: https://github.com/workos/workos-ruby/blob/main/_autodocs/api-reference/organizations.md
Retrieves a specific organization using its unique ID. This is the standard way to fetch details for an existing organization.
```ruby
org = client.organizations.get_organization(
id: "org_123",
request_options: {}
)
```
--------------------------------
### PKCE Usage for Public Clients
Source: https://github.com/workos/workos-ruby/blob/main/_autodocs/api-reference/public-client.md
Demonstrates the correct method for generating an authorization URL with PKCE for public clients. Avoid using the server-side authorization URL method with public clients as it does not generate the necessary PKCE parameters.
```ruby
# ✅ CORRECT: Use PKCE for public clients
url, verifier, state = public_client.user_management.get_authorization_url_with_pkce(...)
# ❌ WRONG: Using server-side authorization URL in public client
url = public_client.user_management.get_authorization_url(...) # Doesn't generate PKCE
```
--------------------------------
### Get Single SSO Connection by ID
Source: https://github.com/workos/workos-ruby/blob/main/_autodocs/api-reference/sso.md
Retrieves a specific SSO connection using its unique identifier. Per-request options can be overridden.
```ruby
connection = client.sso.get_connection(
id: "conn_...",
request_options: {}
)
```
--------------------------------
### Configure WorkOS SDK
Source: https://github.com/workos/workos-ruby/blob/main/_autodocs/README.md
Configure the WorkOS SDK with your API key and client ID. It's recommended to use environment variables for sensitive information.
```ruby
WorkOS.configure do |config|
config.api_key = ENV.fetch("WORKOS_API_KEY")
config.client_id = ENV["WORKOS_CLIENT_ID"]
end
```
--------------------------------
### Configure WorkOS SDK in Initializer
Source: https://github.com/workos/workos-ruby/blob/main/README.md
Configure the WorkOS SDK by setting your API key and client ID in an initializer file. This sets up the client for use throughout your application. You can also configure timeouts and logging.
```ruby
# /config/initializers/workos.rb
require "workos"
WorkOS.configure do |config|
config.api_key = ENV.fetch("WORKOS_API_KEY")
config.client_id = ENV["WORKOS_CLIENT_ID"]
config.timeout = 120
config.logger = Logger.new($stdout)
config.log_level = :info
end
client = WorkOS.client
```
--------------------------------
### Create User Invitation
Source: https://github.com/workos/workos-ruby/blob/main/_autodocs/README.md
Sends an invitation to a user to join an organization.
```ruby
client.user_management.create_user_invitation
```
--------------------------------
### Get Organization by External ID
Source: https://github.com/workos/workos-ruby/blob/main/_autodocs/api-reference/organizations.md
Fetches an organization using its external ID. This is useful for integrating with your own systems that use external identifiers for organizations.
```ruby
org = client.organizations.get_organization_by_external_id(
external_id: "acme_001",
request_options: {}
)
```
--------------------------------
### Get Single Directory Group
Source: https://github.com/workos/workos-ruby/blob/main/_autodocs/api-reference/directory-sync.md
Retrieves a specific directory group using its unique ID. This method is useful for fetching details of a single group.
```ruby
group = client.directory_sync.get_group(
id: "group_123",
request_options: {}
)
```
--------------------------------
### Public Client Initialization for PKCE
Source: https://github.com/workos/workos-ruby/blob/main/README.md
Create a public WorkOS client for browser, mobile, or CLI applications using the PKCE flow. This method generates the authorization URL, verifier, and state parameters needed for the OAuth flow.
```ruby
public_client = WorkOS::PublicClient.create(client_id: "client_123")
url, verifier, state = public_client.user_management.get_authorization_url_with_pkce(
redirect_uri: "https://example.com/callback"
)
```
--------------------------------
### Handle MFA During Login
Source: https://github.com/workos/workos-ruby/blob/main/_autodocs/api-reference/multi-factor-auth.md
Authenticate a user with credentials and check if MFA is required. If so, store the challenge ID and redirect for MFA verification. After successful MFA verification, establish the user session.
```ruby
result = client.user_management.create_authenticate(
client_id: client_id,
client_secret: client_secret,
grant_type: "password",
email: params[:email],
password: params[:password]
)
if result.requires_challenge
challenge_id = result.authentication_challenge_id
session[:mfa_challenge_id] = challenge_id
redirect_to mfa_verify_path
else
set_session_cookie(result)
redirect_to dashboard_path
end
challenge_id = session.fetch(:mfa_challenge_id)
mfa_result = client.multi_factor_auth.verify_challenge(
id: challenge_id,
code: params[:mfa_code]
)
if mfa_result.valid
set_session_cookie(mfa_result)
redirect_to dashboard_path
else
flash[:error] = "Invalid MFA code"
redirect_to mfa_verify_path
end
```
--------------------------------
### Get User by ID
Source: https://github.com/workos/workos-ruby/blob/main/_autodocs/api-reference/user-management.md
Retrieve a specific user's details using their unique user ID. This operation requires the user's ID as a parameter.
```ruby
user = client.user_management.get_user(
id: "user_...",
request_options: {}
)
```
--------------------------------
### Initialize Session Manager
Source: https://github.com/workos/workos-ruby/blob/main/_autodocs/api-reference/session-manager.md
Instantiate the Session Manager. An optional custom encryptor can be provided, otherwise, the default AES-256-GCM encryptor is used.
```ruby
manager = client.session_manager(encryptor: nil)
```
--------------------------------
### Get JWKS for JWT Verification
Source: https://github.com/workos/workos-ruby/blob/main/_autodocs/api-reference/user-management.md
Retrieve the JSON Web Key Set (JWKS) used for verifying JWTs signed by WorkOS. Requires a WorkOS Client ID.
```ruby
jwks = client.user_management.get_jwks(
client_id: "client_...",
request_options: {}
)
```
```ruby
jwks = client.user_management.get_jwks(client_id: "client_123")
jwks.keys.each do |key|
puts "Key ID: #{key.kid}"
puts "Algorithm: #{key.alg}"
end
```
--------------------------------
### Iterate All Organizations
Source: https://github.com/workos/workos-ruby/blob/main/_autodocs/api-reference/organizations.md
Demonstrates how to iterate through all organizations using auto-paging. This is useful when you need to process every organization without manually handling pagination.
```ruby
# Iterate all organizations
organizations = client.organizations.list_organizations(limit: 100)
organizations.auto_paging_each do |org|
puts "#{org.id}: #{org.name} (#{org.domains.join(', ')})"
end
```
--------------------------------
### Manage Tenant-Specific Clients
Source: https://github.com/workos/workos-ruby/blob/main/_autodocs/api-reference/client.md
Implement a `TenantManager` to create and manage WorkOS clients specific to each tenant. This pattern involves fetching tenant API keys and initializing a new `WorkOS::Client` instance with the appropriate credentials and logger configuration. It also includes a method to reset a client for a given tenant.
```ruby
class TenantManager
def client_for(tenant_id)
api_keys = TenantDatabase.fetch(tenant_id)
@clients ||= {}
@clients[tenant_id] ||= WorkOS::Client.new(
api_key: api_keys[:api_key],
client_id: api_keys[:client_id],
logger: Rails.logger,
log_level: :info
)
end
def reset_client(tenant_id)
@clients[tenant_id]&.shutdown
@clients.delete(tenant_id)
end
end
# Usage
manager = TenantManager.new
org = manager.client_for("tenant_abc").organizations.list_organizations
```
--------------------------------
### Create Organization
Source: https://github.com/workos/workos-ruby/blob/main/_autodocs/api-reference/organizations.md
Create a new organization with a specified name. Default values are used if not provided.
```ruby
# Create with defaults
org = client.organizations.create_organization(name: "New Org")
```
--------------------------------
### Create Organization with Domain Data
Source: https://github.com/workos/workos-ruby/blob/main/_autodocs/types.md
Use this to create an organization and associate domain data with it. The domain verification state can be 'verified', 'pending', or 'unverified'.
```ruby
domain_data = [
{
domain: "example.com",
verification_state: "verified" # or "pending" or "unverified"
}
]
org = client.organizations.create_organization(
name: "Example Inc",
domain_data: domain_data
)
```
--------------------------------
### Retry API Calls with Exponential Backoff
Source: https://github.com/workos/workos-ruby/blob/main/_autodocs/errors.md
Implement retries for API calls using the exponential_backoff gem. This example retries listing organizations up to 5 times with a base sleep of 1 second.
```ruby
require "exponential_backoff"
result = ExponentialBackoff.perform(
max_tries: 5,
base_sleep_seconds: 1
) do
client.organizations.list_organizations(limit: 100)
end
```
--------------------------------
### Rails AuthHelper for Session Management
Source: https://github.com/workos/workos-ruby/blob/main/_autodocs/api-reference/session-manager.md
Helper module for Rails applications to manage user sessions. It provides methods to get the current session, user, check sign-in status, and retrieve the organization ID.
```ruby
# app/helpers/auth_helper.rb
module AuthHelper
def current_session
return nil unless cookies["wos-session"]
@current_session ||= WorkOS.client.session_manager.authenticate(
seal_data: cookies["wos-session"],
cookie_password: ENV.fetch("COOKIE_PASSWORD")
)
end
def current_user
current_session&.user
end
def signed_in?
current_session&.authenticated == true
end
def current_organization_id
current_session&.organization_id
end
end
```
--------------------------------
### WorkOS Ruby SDK Module Architecture
Source: https://github.com/workos/workos-ruby/blob/main/_autodocs/overview.md
Illustrates the module structure of the WorkOS Ruby SDK, showing how to access various services via the WorkOS::Client.
```ruby
WorkOS::Client
├── .organizations (WorkOS::Organizations)
├── .user_management (WorkOS::UserManagement)
├── .sso (WorkOS::SSO)
├── .directory_sync (WorkOS::DirectorySync)
├── .multi_factor_auth (WorkOS::MultiFactorAuth)
├── .webhooks (WorkOS::Webhooks)
├── .admin_portal (WorkOS::AdminPortal)
├── .audit_logs (WorkOS::AuditLogs)
├── .api_keys (WorkOS::ApiKeys)
├── .authorization (WorkOS::Authorization)
├── .groups (WorkOS::Groups)
├── .organization_domains (WorkOS::OrganizationDomains)
├── .organization_membership (WorkOS::OrganizationMembershipService)
├── .events (WorkOS::Events)
├── .feature_flags (WorkOS::FeatureFlags)
├── .vault (WorkOS::Vault)
├── .pipes (WorkOS::Pipes)
├── .pipes_provider (WorkOS::PipesProvider)
├── .radar (WorkOS::Radar)
├── .connect (WorkOS::Connect)
├── .client_api (WorkOS::ClientApi)
├── .widgets (WorkOS::Widgets)
├── .passwordless (WorkOS::Passwordless)
├── .session_manager (WorkOS::SessionManager)
├── .actions (WorkOS::Actions)
└── .pkce (WorkOS::PKCE)
```