### Install Stytch .NET Library using .NET CLI Source: https://github.com/stytchauth/stytch-dotnet/blob/main/README.md This snippet shows how to add the Stytch .NET package to your project using the .NET command-line interface. ```bash dotnet add package Stytch.net ``` -------------------------------- ### Authenticate Stytch Magic Link Token in C# Source: https://github.com/stytchauth/stytch-dotnet/blob/main/README.md Provides an example of how to authenticate a magic link token received from Stytch to verify a user's identity in a B2C application. ```csharp client.MagicLinks.Authenticate(new AuthenticateRequest(token: "DOYoip3rvIMMW5lgItikFK-Ak1CfMsgjuiCyI7uuU94=")); ``` -------------------------------- ### Get User by ID with Stytch .NET Source: https://context7.com/stytchauth/stytch-dotnet/llms.txt Retrieves user information by their unique user ID. The response includes the user's name, email, phone number, creation date, and status. ```csharp using Stytch.net.Models; var response = await client.Users.Get(new UsersGetRequest( userId: "user-test-e3795c81-f849-4167-bfda-e4a6e9c280fd" )); var user = response.User; Console.WriteLine($"User name: {user.Name.FirstName} {user.Name.LastName}"); Console.WriteLine($"Email: {user.Emails[0].Email}"); Console.WriteLine($"Phone: {user.PhoneNumbers.Count > 0 ? user.PhoneNumbers[0].PhoneNumber : "None"}"); Console.WriteLine($"Created at: {user.CreatedAt}"); Console.WriteLine($"Status: {user.Status}"); ``` -------------------------------- ### Get User Sessions with Stytch .NET Source: https://context7.com/stytchauth/stytch-dotnet/llms.txt Retrieves all active sessions for a given user ID. It takes a user ID as input and returns a list of session objects, including their IDs and last accessed times. ```csharp using Stytch.net.Models; var response = await client.Sessions.Get(new SessionsGetRequest( userId: "user-test-e3795c81-f849-4167-bfda-e4a6e9c280fd" )); Console.WriteLine($"Found {response.Sessions.Count} active sessions"); foreach (var session in response.Sessions) { Console.WriteLine($"Session ID: {session.SessionId}"); Console.WriteLine($"Last accessed: {session.LastAccessedAt}"); } ``` -------------------------------- ### Get B2B RBAC Policy using C# Source: https://context7.com/stytchauth/stytch-dotnet/llms.txt Retrieves the active Role-Based Access Control (RBAC) policy for an organization. Requires the Stytch.net.Models namespace. It returns details about roles, permissions, resources, and their associated actions. Useful for authorization checks. ```csharp using Stytch.net.Models; var response = await b2bClient.RBAC.Policy(new B2BRBACPolicyRequest()); Console.WriteLine($"Policy roles: {response.Policy.Roles.Count}"); foreach (var role in response.Policy.Roles) { Console.WriteLine($"Role: {role.RoleId} - {role.Description}"); foreach (var permission in role.Permissions) { Console.WriteLine($" - {permission.ResourceId}: {string.Join(", ", permission.Actions)}"); } } Console.WriteLine($"Policy resources: {response.Policy.Resources.Count}"); foreach (var resource in response.Policy.Resources) { Console.WriteLine($"Resource: {resource.ResourceId} - {resource.Description}"); Console.WriteLine($" Available actions: {string.Join(", ", resource.Actions)}"); } ``` -------------------------------- ### Get B2B Organization by ID in C# Source: https://context7.com/stytchauth/stytch-dotnet/llms.txt Retrieves detailed information about a specific B2B organization using its ID. It takes an organization ID as input and returns various details including the organization's name, slug, email domains, and SSO status. ```csharp using Stytch.net.Models; var response = await b2bClient.Organizations.Get(new B2BOrganizationsGetRequest( organizationId: "organization-test-07971b06-ac8b-4cdb-9c15-63b17e653931" )); var org = response.Organization; Console.WriteLine($"Name: {org.OrganizationName}"); Console.WriteLine($"Slug: {org.OrganizationSlug}"); Console.WriteLine($"Email domains: {string.Join(", ", org.EmailAllowedDomains)}"); Console.WriteLine($"SSO enabled: {org.SsoActiveConnections.Count > 0}"); ``` -------------------------------- ### Create Stytch B2BClient in C# Source: https://github.com/stytchauth/stytch-dotnet/blob/main/README.md Illustrates the initialization of the Stytch B2BClient, necessary for integrating Stytch's business-to-business authentication features. Requires project credentials. ```csharp using Stytch.net.Clients; var client = new Stytch.net.Clients.B2BClient(new ClientConfig { ProjectId = "project-live-c60c0abe-c25a-4472-a9ed-320c6667d317", ProjectSecret = "secret-live-80JASucyk7z_G8Z-7dVwZVGXL5NT_qGAQ2I=" }); ``` -------------------------------- ### GET /b2b/rbac/policy Source: https://context7.com/stytchauth/stytch-dotnet/llms.txt Retrieves the active RBAC (Role-Based Access Control) policy for the organization. ```APIDOC ## GET /b2b/rbac/policy ### Description Retrieve the active RBAC policy for authorization checks. ### Method GET ### Endpoint /b2b/rbac/policy ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example None ### Response #### Success Response (200) - **policy** (object) - The RBAC policy object. - **roles** (array) - A list of roles in the policy. - **roleId** (string) - The ID of the role. - **description** (string) - The description of the role. - **permissions** (array) - A list of permissions associated with the role. - **resourceId** (string) - The ID of the resource. - **actions** (array of strings) - A list of actions allowed for the resource. - **resources** (array) - A list of resources in the policy. - **resourceId** (string) - The ID of the resource. - **description** (string) - The description of the resource. - **actions** (array of strings) - A list of all available actions for the resource. #### Response Example ```json { "policy": { "roles": [ { "roleId": "admin", "description": "Administrator role", "permissions": [ { "resourceId": "users", "actions": ["read", "write", "delete"] } ] } ], "resources": [ { "resourceId": "users", "description": "User management", "actions": ["read", "write", "delete"] } ] } } ``` ``` -------------------------------- ### Create Stytch ConsumerClient in C# Source: https://github.com/stytchauth/stytch-dotnet/blob/main/README.md Demonstrates how to initialize the Stytch ConsumerClient with project credentials for B2C applications. This client is used to interact with Stytch's B2C authentication products. ```csharp using Stytch.net.Clients; var client = new Stytch.net.Clients.ConsumerClient(new ClientConfig { ProjectId = "project-live-c60c0abe-c25a-4472-a9ed-320c6667d317", ProjectSecret = "secret-live-80JASucyk7z_G8Z-7dVwZVGXL5NT_qGAQ2I=" }); ``` -------------------------------- ### Initialize Stytch B2B Client - C# Source: https://context7.com/stytchauth/stytch-dotnet/llms.txt Initializes the Stytch B2BClient for business authentication flows, supporting organization and member management. The client automatically configures the environment based on the provided Project ID. ```csharp using Stytch.net.Clients; var b2bClient = new B2BClient(new ClientConfig { ProjectId = "project-live-c60c0abe-c25a-4472-a9ed-320c6667d317", ProjectSecret = "secret-live-80JASucyk7z_G8Z-7dVwZVGXL5NT_qGAQ2I=" }); // The client automatically configures the environment based on project ID // project-test-* uses https://test.stytch.com // project-live-* uses https://api.stytch.com ``` -------------------------------- ### Client Initialization (B2B) Source: https://context7.com/stytchauth/stytch-dotnet/llms.txt Initialize the B2BClient for B2B authentication and organization management flows using your Stytch project credentials. The client automatically configures the correct environment based on the Project ID. ```APIDOC ## Initialize B2B Client Initialize the B2B client for business authentication flows with organization and member management. ### Method Not Applicable (Initialization) ### Endpoint Not Applicable (Initialization) ### Parameters #### Request Body (Conceptual) - **ProjectId** (string) - Required - Your Stytch Project ID. - **ProjectSecret** (string) - Required - Your Stytch Project Secret. ### Request Example ```csharp using Stytch.net.Clients; var b2bClient = new B2BClient(new ClientConfig { ProjectId = "project-live-c60c0abe-c25a-4472-a9ed-320c6667d317", ProjectSecret = "secret-live-80JASucyk7z_G8Z-7dVwZVGXL5NT_qGAQ2I=" }); // The client automatically configures the environment based on project ID // project-test-* uses https://test.stytch.com // project-live-* uses https://api.stytch.com ``` ### Response Not Applicable (Initialization returns a client object) ``` -------------------------------- ### Log User into B2B Organization via Email in C# Source: https://github.com/stytchauth/stytch-dotnet/blob/main/README.md Shows how to log in or sign up a user for a specific organization using email magic links in a B2B context. Requires the organization ID and user's email address. ```csharp client.MagicLinks.Email.LoginOrSignup(new B2BMagicLinksEmailLoginOrSignupRequest(){ OrganizationId = "organization-id-from-create-response-...", EmailAddress = "admin@acme.co", })); ``` -------------------------------- ### Initialize Stytch Consumer Client (B2C) - C# Source: https://context7.com/stytchauth/stytch-dotnet/llms.txt Initializes the Stytch ConsumerClient for B2C authentication flows using project credentials. Supports test and live environments, and allows for custom HttpClient configuration for advanced scenarios. ```csharp using Stytch.net.Clients; // Initialize with test credentials var client = new ConsumerClient(new ClientConfig { ProjectId = "project-test-11111111-1111-1111-1111-111111111111", ProjectSecret = "secret-test-111111111111111111111111111=" }); // Initialize with live credentials var liveClient = new ConsumerClient(new ClientConfig { ProjectId = "project-live-c60c0abe-c25a-4472-a9ed-320c6667d317", ProjectSecret = "secret-live-80JASucyk7z_G8Z-7dVwZVGXL5NT_qGAQ2I=" }); // Initialize with custom HttpClient for advanced scenarios var customHttpClient = new HttpClient(); customHttpClient.Timeout = TimeSpan.FromSeconds(30); var clientWithCustomHttp = new ConsumerClient(new ClientConfig { ProjectId = "project-test-11111111-1111-1111-1111-111111111111", ProjectSecret = "secret-test-111111111111111111111111111=", HttpClient = customHttpClient }); ``` -------------------------------- ### Create User with Password - C# Source: https://context7.com/stytchauth/stytch-dotnet/llms.txt Creates a new user account using an email address and password. This method handles user creation and can initiate a new session with a specified duration. Error handling for duplicate emails and weak passwords is included. ```csharp using Stytch.net.Models; try { var response = await client.Passwords.Create(new PasswordsCreateRequest( email: "newuser@example.com", password: "SecureP@ssw0rd123" ) { SessionDurationMinutes = 60, Name = new Name { FirstName = "John", LastName = "Doe" } }); Console.WriteLine($"User created: {response.UserId}"); Console.WriteLine($"Email verified: {response.EmailVerified}"); Console.WriteLine($"Session token: {response.SessionToken}"); } catch (StytchApiException ex) { if (ex.ErrorType == "duplicate_email") { Console.WriteLine("Email already exists"); } else if (ex.ErrorType == "password_too_weak") { Console.WriteLine("Password does not meet strength requirements"); } } ``` -------------------------------- ### Client Initialization (B2C) Source: https://context7.com/stytchauth/stytch-dotnet/llms.txt Initialize the ConsumerClient for B2C authentication flows using your Stytch project credentials. Supports test and live environments, and allows for custom HttpClient configuration. ```APIDOC ## Initialize Consumer Client (B2C) Initialize the consumer client for B2C authentication flows with project credentials from the Stytch dashboard. ### Method Not Applicable (Initialization) ### Endpoint Not Applicable (Initialization) ### Parameters #### Request Body (Conceptual) - **ProjectId** (string) - Required - Your Stytch Project ID. - **ProjectSecret** (string) - Required - Your Stytch Project Secret. - **HttpClient** (HttpClient) - Optional - A custom HttpClient instance for advanced scenarios. ### Request Example ```csharp using Stytch.net.Clients; // Initialize with test credentials var client = new ConsumerClient(new ClientConfig { ProjectId = "project-test-11111111-1111-1111-1111-111111111111", ProjectSecret = "secret-test-111111111111111111111111111=" }); // Initialize with live credentials var liveClient = new ConsumerClient(new ClientConfig { ProjectId = "project-live-c60c0abe-c25a-4472-a9ed-320c6667d317", ProjectSecret = "secret-live-80JASucyk7z_G8Z-7dVwZVGXL5NT_qGAQ2I=" }); // Initialize with custom HttpClient for advanced scenarios var customHttpClient = new HttpClient(); customHttpClient.Timeout = TimeSpan.FromSeconds(30); var clientWithCustomHttp = new ConsumerClient(new ClientConfig { ProjectId = "project-test-11111111-1111-1111-1111-111111111111", ProjectSecret = "secret-test-111111111111111111111111111=", HttpClient = customHttpClient }); ``` ### Response Not Applicable (Initialization returns a client object) ``` -------------------------------- ### Create Stytch Organization in C# Source: https://github.com/stytchauth/stytch-dotnet/blob/main/README.md Demonstrates the creation of a new organization within Stytch for B2B use cases. This involves specifying organization details like name, slug, and email domain restrictions. ```csharp client.Organizations.Create(new B2BOrganizationsCreateRequest(organizationName: "Acme Co"){ OrganizationSlug = "acme-co", EmailAllowedDomains = ["acme.co"], EmailJITProvisioning = "RESTRICTED" }); ``` -------------------------------- ### Password Authentication APIs Source: https://context7.com/stytchauth/stytch-dotnet/llms.txt APIs for creating users with email and password, authenticating existing users, and checking password strength. ```APIDOC ## POST /passwords/create ### Description Creates a new user with email and password. ### Method POST ### Endpoint /passwords/create ### Parameters #### Request Body - **email** (string) - Required - The user's email address. - **password** (string) - Required - The user's chosen password. - **session_duration_minutes** (integer) - Optional - The desired duration for the user's session in minutes. - **name** (object) - Optional - User's name. - **first_name** (string) - Optional - User's first name. - **last_name** (string) - Optional - User's last name. ### Response #### Success Response (200) - **user_id** (string) - The ID of the created user. - **email_verified** (boolean) - Indicates if the user's email has been verified. - **session_token** (string) - A token representing the user's session. #### Error Response (400) - **error_type** (string) - Type of error (e.g., "duplicate_email", "password_too_weak"). ### Request Example ```json { "email": "newuser@example.com", "password": "SecureP@ssw0rd123", "session_duration_minutes": 60, "name": { "first_name": "John", "last_name": "Doe" } } ``` ### Response Example ```json { "user_id": "user-test-abc123def456", "email_verified": false, "session_token": "some_session_token" } ``` ## POST /passwords/authenticate ### Description Authenticates an existing user with email and password. ### Method POST ### Endpoint /passwords/authenticate ### Parameters #### Request Body - **email** (string) - Required - The user's email address. - **password** (string) - Required - The user's password. - **session_duration_minutes** (integer) - Optional - The desired duration for the user's session in minutes. ### Response #### Success Response (200) - **user_id** (string) - The ID of the authenticated user. - **session_jwt** (string) - A JWT representing the user's session. ### Request Example ```json { "email": "user@example.com", "password": "UserP@ssw0rd123", "session_duration_minutes": 60 } ``` ### Response Example ```json { "user_id": "user-test-abc123def456", "session_jwt": "some_session_jwt" } ``` ## POST /passwords/strength_check ### Description Validates password strength before creating an account or during password updates. ### Method POST ### Endpoint /passwords/strength_check ### Parameters #### Request Body - **password** (string) - Required - The password to check. - **email** (string) - Optional - The user's email, used for customized strength checks. ### Response #### Success Response (200) - **valid_password** (boolean) - Indicates if the password meets the strength requirements. - **score** (integer) - A numerical score representing the password strength. - **feedback** (object) - Optional - Provides feedback on password strength. - **warning** (string) - A general warning message. - **suggestions** (array of strings) - Specific suggestions for improving the password. ### Request Example ```json { "password": "UserP@ssw0rd123", "email": "user@example.com" } ``` ### Response Example ```json { "valid_password": true, "score": 85, "feedback": { "warning": "Strong password!", "suggestions": [] } } ``` ``` -------------------------------- ### Send B2C Email Magic Link in C# Source: https://github.com/stytchauth/stytch-dotnet/blob/main/README.md Shows how to send a magic link via email for user login or signup in a B2C context using the Stytch .NET library. Requires configuring login and signup URLs. ```csharp client.OTPs.Email.LoginOrCreate(new OTPsEmailLoginOrCreateRequest(email: "sandbox@stytch.com"){ LoginMagicLinkUrl = "https://example.com/authenticate", SignupMagicLinkUrl = "https://example.com/authenticate" }); ``` -------------------------------- ### Create B2B Organization in C# Source: https://context7.com/stytchauth/stytch-dotnet/llms.txt Creates a new B2B organization. This function requires the organization name and allows configuration of optional settings such as organization slug, allowed email domains, provisioning, invites, and authentication methods. It returns the newly created organization's ID and slug. ```csharp using Stytch.net.Models; var response = await b2bClient.Organizations.Create(new B2BOrganizationsCreateRequest( organizationName: "Acme Corporation" ) { OrganizationSlug = "acme-corp", EmailAllowedDomains = new List { "acme.com", "acme.co" }, EmailJitProvisioning = "RESTRICTED", EmailInvites = "ALL_ALLOWED", AuthMethods = "ALL_ALLOWED", AllowedAuthMethods = new List { "sso", "magic_link", "password" } }); Console.WriteLine($"Organization created: {response.Organization.OrganizationId}"); Console.WriteLine($"Organization slug: {response.Organization.OrganizationSlug}"); ``` -------------------------------- ### POST /b2b/passwords/email/reset_start Source: https://context7.com/stytchauth/stytch-dotnet/llms.txt Initiates the B2B password reset process by sending a reset email to a member. ```APIDOC ## POST /b2b/passwords/email/reset_start ### Description Send password reset email to a member. ### Method POST ### Endpoint /b2b/passwords/email/reset_start ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **organizationId** (string) - Required - The ID of the organization. - **emailAddress** (string) - Required - The email address of the member. - **resetPasswordRedirectUrl** (string) - Optional - The URL to redirect the user to after resetting their password. - **resetPasswordExpirationMinutes** (integer) - Optional - The expiration time for the reset password link in minutes. ### Request Example ```json { "organizationId": "organization-test-07971b06-ac8b-4cdb-9c15-63b17e653931", "emailAddress": "member@acme.com", "resetPasswordRedirectUrl": "https://app.acme.com/reset-password", "resetPasswordExpirationMinutes": 30 } ``` ### Response #### Success Response (200) - **memberId** (string) - The ID of the member for whom the reset email was sent. #### Response Example ```json { "memberId": "member-test-123" } ``` ``` -------------------------------- ### Create User with Stytch .NET Source: https://context7.com/stytchauth/stytch-dotnet/llms.txt Creates a new user programmatically. This method allows specifying email, name, and custom attributes. It returns the new user's ID and email ID upon successful creation. ```csharp using Stytch.net.Models; var response = await client.Users.Create(new UsersCreateRequest { Email = "newuser@example.com", Name = new Name { FirstName = "Jane", LastName = "Smith" }, Attributes = new UserAttributes { CustomAttributes = new Dictionary { { "plan", "premium" }, { "signup_source", "mobile_app" } } } }); Console.WriteLine($"User created: {response.UserId}"); Console.WriteLine($"Email ID: {response.User.Emails[0].EmailId}"); ``` -------------------------------- ### B2B Magic Links API Source: https://context7.com/stytchauth/stytch-dotnet/llms.txt Manage B2B magic links for organization login and authentication. ```APIDOC ## B2B Magic Links API ### Send B2B Magic Link ### Description Send a magic link to a member for organization login. ### Method POST ### Endpoint /b2b/magic-links/email ### Parameters #### Request Body - **organization_id** (string) - Required - The ID of the organization. - **email_address** (string) - Required - The email address of the member. - **login_redirect_url** (string) - Required - The URL to redirect to after login. - **signup_redirect_url** (string) - Required - The URL to redirect to after signup. ### Request Example ```json { "organization_id": "organization-test-07971b06-ac8b-4cdb-9c15-63b17e653931", "email_address": "admin@acme.com", "login_redirect_url": "https://app.acme.com/authenticate", "signup_redirect_url": "https://app.acme.com/authenticate" } ``` ### Response #### Success Response (200) - **member_id** (string) - The ID of the member. - **member_email_id** (string) - The ID of the member's email. #### Response Example ```json { "member_id": "member-12345", "member_email_id": "email-abcde" } ``` ### Authenticate B2B Magic Link ### Description Authenticate a member using a magic link token. ### Method POST ### Endpoint /b2b/magic-links/authenticate ### Parameters #### Request Body - **magic_links_token** (string) - Required - The magic link token received from the callback. - **session_duration_minutes** (integer) - Optional - The duration of the session in minutes. ### Request Example ```json { "magic_links_token": "DOYoip3rvIMMW5lgItikFK-Ak1CfMsgjuiCyI7uuU94=", "session_duration_minutes": 60 } ``` ### Response #### Success Response (200) - **member_id** (string) - The ID of the authenticated member. - **organization_id** (string) - The ID of the organization. - **session_token** (string) - The session token for the authenticated member. - **session_jwt** (string) - The session JWT for the authenticated member. #### Response Example ```json { "member_id": "member-12345", "organization_id": "org-test-07971b06-ac8b-4cdb-9c15-63b17e653931", "session_token": "session-token-abcde", "session_jwt": "ey..."."..." } ``` ``` -------------------------------- ### Send Magic Link Email - C# Source: https://context7.com/stytchauth/stytch-dotnet/llms.txt Sends a magic link authentication email to a user using the Stytch ConsumerClient. Allows configuration of login/signup URLs and expiration times. Includes error handling for Stytch API exceptions. ```csharp using Stytch.net.Models; using Stytch.net.Exceptions; try { var response = await client.MagicLinks.Email.Send(new MagicLinksEmailSendRequest( email: "user@example.com" ) { LoginMagicLinkUrl = "https://example.com/authenticate", SignupMagicLinkUrl = "https://example.com/authenticate", LoginExpirationMinutes = 60, SignupExpirationMinutes = 1440 }); Console.WriteLine($"Magic link sent to user: {response.UserId}"); Console.WriteLine($"Email ID: {response.EmailId}"); } catch (StytchApiException ex) { Console.WriteLine($"Error: {ex.ErrorType} - {ex.ErrorMessage}"); } ``` -------------------------------- ### POST /b2b/organizations/members/create Source: https://context7.com/stytchauth/stytch-dotnet/llms.txt Adds a new member to an organization. This allows administrators to invite or add new users to their organization. ```APIDOC ## POST /b2b/organizations/members/create ### Description Add a new member to an organization. ### Method POST ### Endpoint /b2b/organizations/members/create ### Parameters #### Request Body - **organizationId** (string) - Required - The ID of the organization to add the member to. - **emailAddress** (string) - Required - The email address of the new member. - **Name** (string) - Optional - The full name of the member. - **IsBreakglass** (boolean) - Optional - Whether this is a breakglass user. - **MfaPhoneNumber** (string) - Optional - The MFA phone number for the member. - **Roles** (array of strings) - Optional - The roles to assign to the member. ### Request Example ```json { "organizationId": "organization-test-07971b06-ac8b-4cdb-9c15-63b17e653931", "emailAddress": "newmember@acme.com", "Name": "Jane Doe", "IsBreakglass": false, "MfaPhoneNumber": "+12025551234", "Roles": ["admin", "developer"] } ``` ### Response #### Success Response (200) - **MemberId** (string) - The ID of the newly created member. - **Member** (object) - Details of the created member. - **EmailAddress** (string) - The email address of the member. #### Response Example ```json { "MemberId": "member-test-abcde-12345", "Member": { "EmailAddress": "newmember@acme.com" } } ``` ``` -------------------------------- ### Authenticate with Password - C# Source: https://context7.com/stytchauth/stytch-dotnet/llms.txt Authenticates an existing user by verifying their email and password. This method is used for login functionality and returns a session JWT upon successful authentication. It requires the user's email and password. ```csharp using Stytch.net.Models; var response = await client.Passwords.Authenticate(new PasswordsAuthenticateRequest( email: "user@example.com", password: "UserP@ssw0rd123" ) { SessionDurationMinutes = 60 }); Console.WriteLine($"User authenticated: {response.UserId}"); Console.WriteLine($"Session JWT: {response.SessionJwt}"); ``` -------------------------------- ### Create B2B Member in Organization Source: https://context7.com/stytchauth/stytch-dotnet/llms.txt Adds a new member to a specific organization. Requires the Stytch .NET SDK and organization ID. Supports setting member name, MFA phone number, and initial roles. ```csharp using Stytch.net.Models; var response = await b2bClient.Organizations.Members.Create(new B2BOrganizationsMembersCreateRequest( organizationId: "organization-test-07971b06-ac8b-4cdb-9c15-63b17e653931", emailAddress: "newmember@acme.com" ) { Name = "Jane Doe", IsBreakglass = false, MfaPhoneNumber = "+12025551234", Roles = new List { "admin", "developer" } }); Console.WriteLine($"Member created: {response.MemberId}"); Console.WriteLine($"Member email ID: {response.Member.EmailAddress}"); ``` -------------------------------- ### B2B Organizations API Source: https://context7.com/stytchauth/stytch-dotnet/llms.txt Manage B2B organizations, including creation, retrieval, update, and search. ```APIDOC ## B2B Organizations API ### Create Organization ### Description Create a new B2B organization. ### Method POST ### Endpoint /b2b/organizations ### Parameters #### Request Body - **organization_name** (string) - Required - The name of the organization. - **organization_slug** (string) - Optional - A unique slug for the organization. - **email_allowed_domains** (array of strings) - Optional - Domains allowed for email-based access. - **email_jit_provisioning** (string) - Optional - Controls Just-In-Time provisioning for email access (e.g., "RESTRICTED", "ALL_ALLOWED"). - **email_invites** (string) - Optional - Controls email invites (e.g., "ALL_ALLOWED", "RESTRICTED"). - **auth_methods** (string) - Optional - Controls allowed authentication methods (e.g., "ALL_ALLOWED"). - **allowed_auth_methods** (array of strings) - Optional - Specifies allowed authentication methods (e.g., "sso", "magic_link", "password"). ### Request Example ```json { "organization_name": "Acme Corporation", "organization_slug": "acme-corp", "email_allowed_domains": ["acme.com", "acme.co"], "email_jit_provisioning": "RESTRICTED", "email_invites": "ALL_ALLOWED", "auth_methods": "ALL_ALLOWED", "allowed_auth_methods": ["sso", "magic_link", "password"] } ``` ### Response #### Success Response (200) - **organization** (object) - Details of the created organization. - **organization_id** (string) - The ID of the organization. - **organization_slug** (string) - The slug of the organization. #### Response Example ```json { "organization": { "organization_id": "org-test-07971b06-ac8b-4cdb-9c15-63b17e653931", "organization_slug": "acme-corp" } } ``` ### Get Organization ### Description Retrieve organization details by ID. ### Method GET ### Endpoint /b2b/organizations/{organization_id} ### Parameters #### Path Parameters - **organization_id** (string) - Required - The ID of the organization to retrieve. ### Response #### Success Response (200) - **organization** (object) - Details of the organization. - **organization_name** (string) - The name of the organization. - **organization_slug** (string) - The slug of the organization. - **email_allowed_domains** (array of strings) - Domains allowed for email-based access. - **sso_active_connections** (array) - List of active SSO connections. #### Response Example ```json { "organization": { "organization_name": "Acme Corporation", "organization_slug": "acme-corp", "email_allowed_domains": ["acme.com"], "sso_active_connections": [] } } ``` ### Update Organization ### Description Update organization settings and authentication policies. ### Method PUT ### Endpoint /b2b/organizations/{organization_id} ### Parameters #### Path Parameters - **organization_id** (string) - Required - The ID of the organization to update. #### Request Body - **organization_name** (string) - Optional - The new name for the organization. - **email_jit_provisioning** (string) - Optional - Controls Just-In-Time provisioning for email access. - **email_invites** (string) - Optional - Controls email invites. #### Headers - **Authorization** (string) - Required - Bearer token for authorization (e.g., "SessionToken member-session-token-here"). ### Request Example ```json { "organization_name": "Acme Corporation Updated", "email_jit_provisioning": "RESTRICTED", "email_invites": "RESTRICTED" } ``` ### Response #### Success Response (200) - **organization** (object) - Details of the updated organization. - **organization_name** (string) - The updated name of the organization. #### Response Example ```json { "organization": { "organization_name": "Acme Corporation Updated" } } ``` ### Search Organizations ### Description Search for organizations with advanced filters. ### Method POST ### Endpoint /b2b/organizations/search ### Parameters #### Request Body - **limit** (integer) - Optional - The maximum number of organizations to return. - **query** (object) - Optional - Search query object. - **operator** (string) - Required - The logical operator for the query (e.g., "OR", "AND"). - **operands** (array) - Required - An array of query operands. - **filter_value** (array of strings) - The value to filter by. ### Request Example ```json { "limit": 10, "query": { "operator": "OR", "operands": [ { "filter_value": ["acme-corp", "example-inc"] } ] } } ``` ### Response #### Success Response (200) - **organizations** (array) - A list of organizations matching the search criteria. - **organization_name** (string) - The name of the organization. - **organization_slug** (string) - The slug of the organization. #### Response Example ```json { "organizations": [ { "organization_name": "Acme Corporation", "organization_slug": "acme-corp" }, { "organization_name": "Example Inc.", "organization_slug": "example-inc" } ] } ``` ``` -------------------------------- ### OAuth Authentication API Source: https://context7.com/stytchauth/stytch-dotnet/llms.txt Complete the OAuth authentication flow by exchanging the OAuth token received from a callback. ```APIDOC ## Authenticate OAuth Token ### Description Complete OAuth authentication flow by exchanging the OAuth token. ### Method POST ### Endpoint /oauth/authenticate ### Parameters #### Request Body - **token** (string) - Required - The OAuth token received from the callback. - **session_duration_minutes** (integer) - Optional - The duration of the session in minutes. ### Request Example ```json { "token": "oauth-token-from-callback", "session_duration_minutes": 60 } ``` ### Response #### Success Response (200) - **user_id** (string) - The ID of the authenticated user. - **provider_type** (string) - The type of OAuth provider used. - **session_token** (string) - The session token for the authenticated user. - **provider_values** (object) - Optional - Provider-specific data. - **email** (string) - The email address associated with the OAuth provider. - **name** (string) - The name associated with the OAuth provider. #### Response Example ```json { "user_id": "user-12345", "provider_type": "google", "session_token": "session-token-abcde", "provider_values": { "email": "user@example.com", "name": "User Name" } } ``` ``` -------------------------------- ### Search Users with Stytch .NET Source: https://context7.com/stytchauth/stytch-dotnet/llms.txt Searches for users based on specified filters and pagination settings. It allows filtering by user ID and returns a list of matching users along with pagination metadata. ```csharp using Stytch.net.Models; var response = await client.Users.Search(new UsersSearchRequest { Limit = 10, Query = new SearchUsersQuery { Operands = new List { new UserIdFilter { FilterValue = new List { "user-test-e3795c81-f849-4167-bfda-e4a6e9c280fd" } } } } }); Console.WriteLine($"Found {response.Results.Count} users"); foreach (var user in response.Results) { Console.WriteLine($"User: {user.UserId} - {user.Emails[0]?.Email}"); } // Handle pagination if (response.ResultsMetadata.NextCursor != null) { Console.WriteLine($"More results available: {response.ResultsMetadata.NextCursor}"); } ``` -------------------------------- ### Update B2B Organization in C# Source: https://context7.com/stytchauth/stytch-dotnet/llms.txt Updates settings and authentication policies for an existing B2B organization. Requires the organization ID and allows modification of the organization name, email provisioning, and invite settings. An optional authorization header with a session token can be provided. ```csharp using Stytch.net.Models; var response = await b2bClient.Organizations.Update( new B2BOrganizationsUpdateRequest( organizationId: "organization-test-07971b06-ac8b-4cdb-9c15-63b17e653931" ) { OrganizationName = "Acme Corporation Updated", EmailJitProvisioning = "RESTRICTED", EmailInvites = "RESTRICTED" }, new B2BOrganizationsUpdateRequestOptions { Authorization = new B2BAuthorizationHeader { SessionToken = "member-session-token-here" } } ); Console.WriteLine($"Organization updated: {response.Organization.OrganizationName}"); ``` -------------------------------- ### B2B Password Authentication using C# Source: https://context7.com/stytchauth/stytch-dotnet/llms.txt Authenticates a member within an organization using their email and password. Requires the Stytch.net.Models namespace. It takes organization ID, email address, and password as input, and returns member and session details. Session duration can be customized. ```csharp using Stytch.net.Models; var response = await b2bClient.Passwords.Authenticate(new B2BPasswordsAuthenticateRequest( organizationId: "organization-test-07971b06-ac8b-4cdb-9c15-63b17e653931", emailAddress: "member@acme.com", password: "SecureP@ssw0rd123" ) { SessionDurationMinutes = 60 }); Console.WriteLine($"Member authenticated: {response.MemberId}"); Console.WriteLine($"Session token: {response.SessionToken}"); Console.WriteLine($"Organization: {response.OrganizationId}"); ``` -------------------------------- ### Handle Stytch API Exceptions in C# Source: https://context7.com/stytchauth/stytch-dotnet/llms.txt Demonstrates how to catch and handle various Stytch API exceptions in C#. It includes handling generic `StytchApiException` for API-level errors, `StytchNetworkException` for network issues, and specific exceptions like `StytchMissingScopesException`, `StytchInvalidPermissionsException`, and `StytchTenancyMismatchException` for B2B scenarios. This allows for granular error management and appropriate user feedback. ```csharp using Stytch.net.Models; using Stytch.net.Exceptions; try { var response = await client.MagicLinks.Authenticate(new MagicLinksAuthenticateRequest( token: "invalid-token" )); } catch (StytchApiException ex) { // API returned an error response Console.WriteLine($"Status code: {ex.StatusCode}"); Console.WriteLine($"Error type: {ex.ErrorType}"); Console.WriteLine($"Error message: {ex.ErrorMessage}"); Console.WriteLine($"Request ID: {ex.RequestId}"); Console.WriteLine($"Documentation: {ex.ErrorUrl}"); // Handle specific error types switch (ex.ErrorType) { case "unable_to_auth_magic_link": Console.WriteLine("Magic link expired or already used"); break; case "user_not_found": Console.WriteLine("User does not exist"); break; case "duplicate_email": Console.WriteLine("Email already registered"); break; } } catch (StytchNetworkException ex) { // Network or unexpected error Console.WriteLine($"Network error: {ex.Message}"); Console.WriteLine($"Response body: {ex.ResponseBody}"); } catch (StytchMissingScopesException ex) { // M2M token missing required scopes Console.WriteLine($"Missing scope: {ex.RequiredScope}"); Console.WriteLine($"Client has: {string.Join(", ", ex.ClientScopes)}"); } catch (StytchInvalidPermissionsException) { // B2B RBAC authorization failed Console.WriteLine("Member does not have required permissions"); } catch (StytchTenancyMismatchException ex) { // B2B organization mismatch Console.WriteLine($"Organization mismatch: {ex.CallerOrganizationId} vs {ex.TargetOrganizationId}"); } ``` -------------------------------- ### Session Management API Source: https://context7.com/stytchauth/stytch-dotnet/llms.txt API for validating and refreshing existing user sessions. ```APIDOC ## POST /sessions/authenticate ### Description Validates and refreshes an existing user session. ### Method POST ### Endpoint /sessions/authenticate ### Parameters #### Request Body - **session_token** (string) - Required - The token of the session to authenticate. - **session_duration_minutes** (integer) - Optional - The desired duration for the refreshed session in minutes. ### Response #### Success Response (200) - **session** (object) - Details about the authenticated session. - **user_id** (string) - The ID of the user associated with the session. - **started_at** (string) - ISO 8601 timestamp of when the session started. - **expires_at** (string) - ISO 8601 timestamp of when the session expires. - **last_accessed_at** (string) - ISO 8601 timestamp of the last session access. - **authentication_factors** (array of objects) - Information about the authentication methods used for the session. - **delivery_method** (string) - The method used for authentication (e.g., "email", "sms"). - **email_factor** (object) - Details if the authentication factor was email-based. - **email_address** (string) - The authenticated email address. #### Error Response (400) - **error_type** (string) - A string indicating the type of error (e.g., "invalid_session_token"). ### Request Example ```json { "session_token": "WJtR5BCy38Szd5AfoDpf0iqFKEt4EE5JhjlWUY7l3FtY", "session_duration_minutes": 60 } ``` ### Response Example ```json { "session": { "user_id": "user-test-abc123def456", "started_at": "2023-10-27T10:00:00Z", "expires_at": "2023-10-27T11:00:00Z", "last_accessed_at": "2023-10-27T10:30:00Z", "authentication_factors": [ { "delivery_method": "email", "email_factor": { "email_address": "user@example.com" } } ] } } ``` ``` -------------------------------- ### Exchange B2B Session to Another Organization Source: https://context7.com/stytchauth/stytch-dotnet/llms.txt Allows a member to switch their active session to a different organization within your Stytch project. Requires the Stytch .NET SDK and current session token. Handles cases where additional authentication might be required. ```csharp using Stytch.net.Models; var response = await b2bClient.Sessions.Exchange(new B2BSessionsExchangeRequest( organizationId: "organization-test-new-org-id", sessionToken: "current-session-token" )); if (response.MemberAuthenticated) { Console.WriteLine("Member successfully authenticated in new organization"); Console.WriteLine($"New session token: {response.SessionToken}"); } else { Console.WriteLine("Member needs to complete additional authentication"); Console.WriteLine($"Intermediate session token: {response.IntermediateSessionToken}"); if (response.PrimaryRequired != null) { Console.WriteLine($"Primary auth methods: {string.Join(", ", response.PrimaryRequired.AllowedAuthMethods)}"); } } ```