### Install Stytch Java SDK Source: https://github.com/stytchauth/stytch-java/blob/main/README.md This snippet shows how to add the Stytch Java SDK to your project's dependencies using Gradle. ```gradle implementation("com.stytch.java:sdk:6.0.0") ``` -------------------------------- ### Publishing to Local Maven Repository - Gradle Source: https://github.com/stytchauth/stytch-java/blob/main/DEVELOPMENT.md This process involves temporarily commenting out signing configurations, publishing the library to your local Maven repository using a Gradle task, adding the local repository to your application's build configuration, and refreshing dependencies. ```bash ./gradlew publishToMavenLocal ``` ```bash ./gradlew --refresh-dependencies ``` -------------------------------- ### WebAuthn/FIDO2 Authentication with Stytch Java SDK Source: https://context7.com/stytchauth/stytch-java/llms.txt Demonstrates how to implement passwordless authentication using WebAuthn/FIDO2 with the Stytch Java SDK. This includes starting and completing registration, as well as starting and completing authentication. It requires Stytch client initialization and user identification. ```kotlin import com.stytch.java.consumer.models.webauthn.WebAuthn.* // Start WebAuthn registration val registerStartResult = client.webauthn.registerStart( RegisterStartRequest( userId = "user-test-16d9ba61-97a1-4ba4-9720-b03761dc50c6", domain = "example.com", userAgent = "Mozilla/5.0...", authenticatorType = AuthenticatorType.PLATFORM, returnPasskeyCredentialOptions = true ) ) when (registerStartResult) { is StytchResult.Success -> { val publicKeyOptions = registerStartResult.value.publicKeyCredentialCreationOptions println("Challenge: ${publicKeyOptions}") // Send publicKeyOptions to frontend for navigator.credentials.create() } is StytchResult.Error -> println("Failed to start registration") } // Complete WebAuthn registration val registerResult = client.webauthn.register( RegisterRequest( userId = "user-test-16d9ba61-97a1-4ba4-9720-b03761dc50c6", publicKeyCredential = "public_key_credential_from_browser", sessionDurationMinutes = 60 ) ) when (registerResult) { is StytchResult.Success -> { println("WebAuthn registered!") println("WebAuthn ID: ${registerResult.value.webauthnRegistrationId}") println("Session token: ${registerResult.value.sessionToken}") } is StytchResult.Error -> println("Registration failed") } // Start WebAuthn authentication val authStartResult = client.webauthn.authenticateStart( AuthenticateStartRequest( userId = "user-test-16d9ba61-97a1-4ba4-9720-b03761dc50c6", domain = "example.com", returnPasskeyCredentialOptions = true ) ) // Complete WebAuthn authentication val authResult = client.webauthn.authenticate( AuthenticateRequest( publicKeyCredential = "public_key_credential_from_browser", sessionDurationMinutes = 60, sessionCustomClaims = mapOf("webauthn_verified" to true) ) ) ``` -------------------------------- ### Stytch B2B SSO: Get SSO Connections (Kotlin) Source: https://context7.com/stytchauth/stytch-java/llms.txt Demonstrates how to retrieve a list of all configured SSO connections for a given organization using the Stytch Java SDK. This is useful for managing or displaying available SSO options. ```kotlin import com.stytch.java.b2b.models.sso.SSO.* // Get SSO connections val connectionsResult = client.sso.getConnections( GetConnectionsRequest( organizationId = "organization-test-07971b06-ac8b-4cdb-9c15-63b17e653931" ) ) ``` -------------------------------- ### Session Management: Authenticate, Get, Revoke (Kotlin) Source: https://context7.com/stytchauth/stytch-java/llms.txt Provides examples for managing user sessions, including authenticating an existing session token, performing local JWT authentication without an API call, authenticating JWT with remote fallback, retrieving all sessions for a user, and revoking a specific session. Session management is crucial for maintaining user login states securely. ```kotlin import com.stytch.java.consumer.models.sessions.Sessions.* // Authenticate existing session val authResult = client.sessions.authenticate( AuthenticateRequest( sessionToken = "mZAYn5aLEqKUlZ_Ad9U_fWr38GaAQ1oFAhT8ds245v7Q", sessionDurationMinutes = 60 ) ) when (authResult) { is StytchResult.Success -> { val session = authResult.value.session println("Session ID: ${session.sessionId}") println("User ID: ${session.userId}") println("Expires at: ${session.expiresAt}") println("Roles: ${session.roles}") println("Authentication factors: ${session.authenticationFactors}") } is StytchResult.Error -> println("Session invalid or expired") } // Authenticate JWT locally without API call val jwtResult = client.sessions.authenticateJwtLocal( jwt = "eyJhbGciOiJSUzI1NiIsInR5cCI6IkpXVCIsImtpZCI6Imp3ay10ZXN0...", maxTokenAgeSeconds = 300, // Force remote validation if older than 5 min leeway = 10 // Clock skew tolerance in seconds ) // Authenticate JWT with remote fallback val jwtRemoteResult = client.sessions.authenticateJwt( jwt = "eyJhbGciOiJSUzI1NiIs...", maxTokenAgeSeconds = 300 ) // Get all sessions for a user val getResult = client.sessions.get( GetRequest(userId = "user-test-16d9ba61-97a1-4ba4-9720-b03761dc50c6") ) when (getResult) { is StytchResult.Success -> { getResult.value.sessions.forEach { session -> println("Session: ${session.sessionId}, Expires: ${session.expiresAt}") } } is StytchResult.Error -> println("Failed to get sessions") } // Revoke session val revokeResult = client.sessions.revoke( RevokeRequest( sessionId = "session-test-fe6c042f-6022-498f-b945-794dc3ac01e5" // Can also use sessionToken or sessionJwt ) ) ``` -------------------------------- ### Async Authentication with Java CompletableFuture Source: https://context7.com/stytchauth/stytch-java/llms.txt Shows how to perform asynchronous user authentication using Java's CompletableFuture. This example illustrates initiating an authentication request and handling the response asynchronously using `thenAccept` and `exceptionally` callbacks. It also includes a blocking `future.get()` for demonstration. ```java import java.util.concurrent.CompletableFuture; // Java CompletableFuture AuthenticateRequest request = new AuthenticateRequest("token-123"); CompletableFuture> future = client.magicLinks.authenticateCompletable(request); future.thenAccept(result -> { if (result instanceof StytchResult.Success) { AuthenticateResponse response = ((StytchResult.Success) result).getValue(); System.out.println("User ID: " + response.getUserId()); System.out.println("Session: " + response.getSessionToken()); } else { StytchException exception = ((StytchResult.Error) result).getException(); System.out.println("Error: " + exception.getReason()); } }).exceptionally(throwable -> { System.err.println("Request failed: " + throwable.getMessage()); return null; }); // Wait for completion (blocking) try { StytchResult result = future.get(); // Handle result } catch (Exception e) { System.err.println("Request failed: " + e.getMessage()); } ``` -------------------------------- ### Authenticate Magic Link Token in Kotlin and Java Source: https://github.com/stytchauth/stytch-java/blob/main/README.md Provides code examples for authenticating a magic link token received by the user. Handles both successful authentication and potential errors. Supports Kotlin and Java. ```kotlin when (val result = client.magicLinks.authenticate( AuthenticateRequest(token = "DOYoip3rvIMMW5lgItikFK-Ak1CfMsgjuiCyI7uuU94=") )) { is StytchResult.Success -> println(result.value) is StytchResult.Error -> println(result.exception) } ``` ```java AuthenticateRequest request = new AuthenticateRequest("DOYoip3rvIMMW5lgItikFK-Ak1CfMsgjuiCyI7uuU94="); StytchResult response = client.magicLinks.authenticateCompletable(request).get(); if (response instanceof StytchResult.Error) { var exception = ((StytchResult.Error) response).getException(); System.out.println(exception.getReason()); } else { System.out.println(((StytchResult.Success) response).getValue()); } ``` -------------------------------- ### Send Magic Link by Email in Kotlin and Java Source: https://github.com/stytchauth/stytch-java/blob/main/README.md Illustrates how to send a magic link for user login or creation via email using the Stytch client. Includes examples for handling success and error responses. Supports both Kotlin and Java. ```kotlin when (val result = client.magicLinks.email.loginOrCreate( LoginOrCreateRequest( email = "email@address.com", loginMagicLinkURL = "https://example.com/login", signupMagicLinkURL = "https://example.com/signup", ) )) { is StytchResult.Success -> println(result.value) is StytchResult.Error -> println(result.exception) } ``` ```java LoginOrCreateRequest request = new LoginOrCreateRequest( "email@address.com", "https://example.com/signup", "https://example.com/login" ); StytchResult response = client.magicLinks.getEmail().loginOrCreateCompletable(request).get(); if (response instanceof StytchResult.Error) { var exception = ((StytchResult.Error) response).getException(); System.out.println(exception.getReason()); } else { System.out.println(((StytchResult.Success) response).getValue()); } ``` -------------------------------- ### Authenticate Magic Link Token (Kotlin/Java) Source: https://context7.com/stytchauth/stytch-java/llms.txt Provides an example of how to authenticate a magic link token received from a callback URL. This process verifies the token and establishes a user session. It includes options for session duration and custom claims, and demonstrates handling success and error responses. ```kotlin import com.stytch.java.consumer.models.magiclinks.MagicLinks.* val result = client.magicLinks.authenticate( AuthenticateRequest( token = "DOYoip3rvIMMW5lgItikFK-Ak1CfMsgjuiCyI7uuU94=", sessionDurationMinutes = 60, sessionCustomClaims = mapOf( "role" to "user", "department" to "engineering" ) ) ) when (result) { is StytchResult.Success -> { val response = result.value println("User ID: ${response.userId}") println("Session Token: ${response.sessionToken}") println("Session JWT: ${response.sessionJwt}") println("User Email: ${response.user.emails.firstOrNull()?.email}") response.session?.let { session -> println("Session ID: ${session.sessionId}") println("Expires at: ${session.expiresAt}") } } is StytchResult.Error -> println("Authentication failed") } ``` ```java import com.stytch.java.consumer.models.magiclinks.MagicLinks.AuthenticateRequest; import com.stytch.java.core.StytchResult; import com.stytch.java.consumer.models.magiclinks.MagicLinks.AuthenticateResponse; import java.util.HashMap; import java.util.Map; Map customClaims = new HashMap<>(); customClaims.put("role", "user"); customClaims.put("department", "engineering"); AuthenticateRequest request = new AuthenticateRequest( "DOYoip3rvIMMW5lgItikFK-Ak1CfMsgjuiCyI7uuU94=", 60, customClaims ); StytchResult response = client.magicLinks.authenticateCompletable(request).get(); if (response instanceof StytchResult.Success) { AuthenticateResponse successResponse = ((StytchResult.Success) response).getValue(); System.out.println("User ID: " + successResponse.userId); System.out.println("Session Token: " + successResponse.sessionToken); System.out.println("Session JWT: " + successResponse.sessionJwt); System.out.println("User Email: " + successResponse.user.emails.get(0).email); if (successResponse.session != null) { System.out.println("Session ID: " + successResponse.session.sessionId); System.out.println("Expires at: " + successResponse.session.expiresAt); } } else { System.out.println("Authentication failed"); } ``` -------------------------------- ### Stytch B2B SSO: Update SAML & OIDC Connections (Kotlin) Source: https://context7.com/stytchauth/stytch-java/llms.txt Provides examples for updating existing SAML and OIDC SSO connections within an organization using the Stytch Java SDK. This includes configuring IdP details for SAML and issuer/URL details for OIDC. ```kotlin import com.stytch.java.b2b.models.sso.SSO.* // Update SAML connection with IdP details val updateResult = client.sso.saml.updateConnection( UpdateConnectionRequest( organizationId = "organization-test-07971b06-ac8b-4cdb-9c15-63b17e653931", connectionId = "saml-connection-test-...", idpEntityId = "https://idp.okta.com/exk1a2b3c4d5e6f7g8h9", idpSsoUrl = "https://idp.okta.com/app/stytch/exk1a2b3c4d5e6f7g8h9/sso/saml", x509Certificate = "-----BEGIN CERTIFICATE-----\nMIIDpDCCAoygAwIBAgIGAXo...", attributeMapping = AttributeMapping( email = "email", firstName = "firstName", lastName = "lastName", fullName = "displayName" ) ) ) // Update OIDC connection val updateOidcResult = client.sso.oidc.updateConnection( UpdateConnectionRequest( organizationId = "organization-test-07971b06-ac8b-4cdb-9c15-63b17e653931", connectionId = "oidc-connection-test-...", displayName = "Azure AD SSO", issuer = "https://login.microsoftonline.com/tenant-id/v2.0", authorizationUrl = "https://login.microsoftonline.com/tenant-id/oauth2/v2.0/authorize", tokenUrl = "https://login.microsoftonline.com/tenant-id/oauth2/v2.0/token", userInfoUrl = "https://graph.microsoft.com/oidc/userinfo", jwksUrl = "https://login.microsoftonline.com/tenant-id/discovery/v2.0/keys" ) ) ``` -------------------------------- ### Error Handling with Stytch Java SDK Source: https://context7.com/stytchauth/stytch-java/llms.txt Provides examples of robust error handling for Stytch API calls in Java and Kotlin. It demonstrates pattern matching on `StytchResult` and handling `StytchException` types, including specific API errors and critical errors, to provide detailed feedback and enable targeted recovery strategies. ```kotlin import com.stytch.java.common.StytchResult import com.stytch.java.common.StytchException // Pattern matching on result when (val result = client.users.get(GetRequest(userId = "user-test-..."))) { is StytchResult.Success -> { val user = result.value.user println("User found: ${user.userId}") } is StytchResult.Error -> { when (val exception = result.exception) { is StytchException.Response -> { val error = exception.reason println("API Error: ${error.errorType}") println("Message: ${error.errorMessage}") println("Status code: ${error.statusCode}") println("Request ID: ${error.requestId}") println("Documentation: ${error.errorUrl}") // Handle specific error types when (error.errorType) { "user_not_found" -> println("User does not exist") "duplicate_email" -> println("Email already in use") "invalid_token" -> println("Token expired or invalid") "unauthorized" -> println("Insufficient permissions") "rate_limited" -> println("Too many requests") else -> println("Unknown error: ${error.errorType}") } } is StytchException.Critical -> { println("Critical error: ${exception.reason.message}") exception.response?.let { println("Response body: $it") } // Log to error tracking system } } } } ``` ```java import com.stytch.java.common.StytchResult; import com.stytch.java.common.StytchException; import com.stytch.java.consumer.models.users.Users.*; // Java error handling StytchResult result = client.users.getCompletable(request).get(); if (result instanceof StytchResult.Error) { StytchException exception = ((StytchResult.Error) result).getException(); if (exception instanceof StytchException.Response) { ErrorResponse error = ((StytchException.Response) exception).getReason(); System.out.println("Error: " + error.getErrorType()); System.out.println("Message: " + error.getErrorMessage()); System.out.println("Status: " + error.getStatusCode()); } } else { GetResponse response = ((StytchResult.Success) result).getValue(); System.out.println("Success: " + response.getUser().getUserId()); } ``` -------------------------------- ### Stytch Java SDK: Get User by ID Source: https://context7.com/stytchauth/stytch-java/llms.txt Retrieves a user's details using their unique user ID. The result is handled to either display user information upon success or indicate if the user was not found. ```kotlin import com.stytch.java.consumer.models.users.Users.* // Get user by ID val getResult = client.users.get( GetRequest(userId = "user-test-16d9ba61-97a1-4ba4-9720-b03761dc50c6") ) when (getResult) { is StytchResult.Success -> { val user = getResult.value.user println("Name: ${user.name?.firstName} ${user.name?.lastName}") println("Email: ${user.emails.firstOrNull()?.email}") println("Phone: ${user.phoneNumbers.firstOrNull()?.phoneNumber}") println("Status: ${user.status}") println("Created: ${user.createdAt}") println("Trusted metadata: ${user.trustedMetadata}") } is StytchResult.Error -> println("User not found") } ``` -------------------------------- ### Initialize Stytch B2B Client in Kotlin and Java Source: https://github.com/stytchauth/stytch-java/blob/main/README.md Demonstrates how to create an instance of the Stytch B2B client using project ID and secret key. This is the first step for interacting with Stytch's B2B services. ```kotlin import com.stytch.java.b2b.StytchB2BClient ... val client = StytchB2BClient( projectId = "project-live-c60c0abe-c25a-4472-a9ed-320c6667d317", secret = "secret-live-80JASucyk7z_G8Z-7dVwZVGXL5NT_qGAQ2I=" ) ``` ```java import com.stytch.java.b2b.StytchB2BClient; ... StytchB2BClient client = new StytchB2BClient( "project-live-c60c0abe-c25a-4472-a9ed-320c6667d317", "secret-live-80JASucyk7z_G8Z-7dVwZVGXL5NT_qGAQ2I=" ); ``` -------------------------------- ### Initialize Stytch Consumer Client (Kotlin/Java) Source: https://context7.com/stytchauth/stytch-java/llms.txt Demonstrates how to initialize the StytchClient for consumer (B2C) applications. It shows basic initialization with project ID and secret, as well as advanced initialization with custom API base URLs. This client is used for passwordless authentication methods. ```kotlin import com.stytch.java.consumer.StytchClient val client = StytchClient( projectId = "project-live-c60c0abe-c25a-4472-a9ed-320c6667d317", secret = "secret-live-80JASucyk7z_G8Z-7dVwZVGXL5NT_qGAQ2I=" ) // With custom configuration val client = StytchClient( projectId = "project-test-...", secret = "secret-test-...", clientConfig = OptionalClientConfig( apiBaseUrl = "https://custom-api.example.com", fraudBaseUrl = "https://custom-fraud.example.com" ) ) ``` ```java import com.stytch.java.consumer.StytchClient; import com.stytch.java.consumer.config.OptionalClientConfig; // Basic initialization StytchClient client = new StytchClient( "project-live-c60c0abe-c25a-4472-a9ed-320c6667d317", "secret-live-80JASucyk7z_G8Z-7dVwZVGXL5NT_qGAQ2I=" ); // With custom configuration StytchClient client = new StytchClient( "project-test-...", "secret-test-...", new OptionalClientConfig( "https://custom-api.example.com", "https://custom-fraud.example.com" ) ); ``` -------------------------------- ### Client Initialization Source: https://context7.com/stytchauth/stytch-java/llms.txt Initialize the Stytch Consumer (B2C) and Business (B2B) clients for your application. ```APIDOC ## Client Initialization ### Description Initialize the Consumer Client for B2C applications and the B2B Client for business applications. ### Consumer Client Initialization ```kotlin import com.stytch.java.consumer.StytchClient val client = StytchClient( projectId = "project-live-c60c0abe-c25a-4472-a9ed-320c6667d317", secret = "secret-live-80JASucyk7z_G8Z-7dVwZVGXL5NT_qGAQ2I=" ) // With custom configuration val client = StytchClient( projectId = "project-test-...", secret = "secret-test-...", clientConfig = OptionalClientConfig( apiBaseUrl = "https://custom-api.example.com", fraudBaseUrl = "https://custom-fraud.example.com" ) ) ``` ### Business (B2B) Client Initialization ```kotlin import com.stytch.java.b2b.StytchB2BClient val client = StytchB2BClient( projectId = "project-live-c60c0abe-c25a-4472-a9ed-320c6667d317", secret = "secret-live-80JASucyk7z_G8Z-7dVwZVGXL5NT_qGAQ2I=" ) // Java initialization StytchB2BClient client = new StytchB2BClient( "project-live-c60c0abe-c25a-4472-a9ed-320c6667d317", "secret-live-80JASucyk7z_G8Z-7dVwZVGXL5NT_qGAQ2I=" ); ``` ``` -------------------------------- ### Create and Authenticate User with Password (Kotlin) Source: https://context7.com/stytchauth/stytch-java/llms.txt This snippet demonstrates how to create a new user with a password and subsequently authenticate an existing user using their email and password. It handles success and error responses, returning user IDs and session tokens upon successful creation or authentication. Dependencies include the Stytch consumer SDK for Kotlin. ```kotlin import com.stytch.java.consumer.models.passwords.Passwords.* import com.stytch.java.consumer.models.users.Users.Name // Create user with password val createResult = client.passwords.create( CreateRequest( email = "user@example.com", password = "SecureP@ssw0rd!123", sessionDurationMinutes = 60, name = Name( firstName = "Jane", middleName = "Marie", lastName = "Doe" ), trustedMetadata = mapOf( "internal_id" to "EMP12345", "verified" to true ), untrustedMetadata = mapOf( "theme" to "dark", "language" to "en" ) ) ) when (createResult) { is StytchResult.Success -> { println("User created: ${createResult.value.userId}") println("Session token: ${createResult.value.sessionToken}") } is StytchResult.Error -> println("Failed to create user") } // Authenticate existing user val authResult = client.passwords.authenticate( AuthenticateRequest( email = "user@example.com", password = "SecureP@ssw0rd!123", sessionDurationMinutes = 60, sessionCustomClaims = mapOf("login_method" to "password") ) ) ``` -------------------------------- ### Manage B2B Organizations with Stytch Java SDK Source: https://context7.com/stytchauth/stytch-java/llms.txt This snippet demonstrates how to perform various operations on B2B organizations using the Stytch Java SDK. It covers creating, retrieving, updating, searching, and deleting organizations. Ensure the Stytch client is properly initialized before use. ```kotlin import com.stytch.java.b2b.models.organizations.Organizations.* // Create organization val createResult = client.organizations.create( CreateRequest( organizationName = "Acme Corporation", organizationSlug = "acme-corp", organizationLogoUrl = "https://acme.com/logo.png", emailAllowedDomains = listOf("acme.com", "acme.co"), emailJitProvisioning = EmailJitProvisioning.RESTRICTED, emailInvites = EmailInvites.ALL_ALLOWED, authMethods = AuthMethods.RESTRICTED, allowedAuthMethods = listOf("sso", "magic_link", "password"), ssoJitProvisioning = SsoJitProvisioning.ALL_ALLOWED, mfaMethods = MfaMethods.ALL_ALLOWED, allowedMfaMethods = listOf("totp", "sms"), mfaPolicy = MfaPolicy.REQUIRED_FOR_ALL ) ) when (createResult) { is StytchResult.Success -> { val org = createResult.value.organization println("Organization created: ${org.organizationId}") println("Name: ${org.organizationName}") println("Slug: ${org.organizationSlug}") } is StytchResult.Error -> println("Failed to create organization") } // Get organization val getResult = client.organizations.get( GetRequest(organizationId = "organization-test-07971b06-ac8b-4cdb-9c15-63b17e653931") ) // Update organization val updateResult = client.organizations.update( UpdateRequest( organizationId = "organization-test-07971b06-ac8b-4cdb-9c15-63b17e653931", organizationName = "Acme Corp (Updated)", organizationSlug = "acme-updated", emailJitProvisioning = EmailJitProvisioning.NOT_ALLOWED, mfaPolicy = MfaPolicy.REQUIRED_FOR_ALL ) ) // Search organizations val searchResult = client.organizations.search( SearchRequest( query = SearchQuery( operator = SearchOperator.AND, operands = listOf( SearchOperand( filterName = "organization_slugs", filterValue = listOf("acme-corp", "example-org") ) ) ), limit = 50 ) ) // Delete organization val deleteResult = client.organizations.delete( DeleteRequest(organizationId = "organization-test-07971b06-ac8b-4cdb-9c15-63b17e653931") ) ``` -------------------------------- ### Initialize Stytch B2B Client (Kotlin/Java) Source: https://context7.com/stytchauth/stytch-java/llms.txt Shows how to initialize the StytchB2BClient for business (B2B) applications, which includes organization and member management features. Initialization requires the project ID and secret. This client is essential for enterprise-level authentication flows. ```kotlin import com.stytch.java.b2b.StytchB2BClient val client = StytchB2BClient( projectId = "project-live-c60c0abe-c25a-4472-a9ed-320c6667d317", secret = "secret-live-80JASucyk7z_G8Z-7dVwZVGXL5NT_qGAQ2I=" ) ``` ```java import com.stytch.java.b2b.StytchB2BClient; // Java initialization StytchB2BClient client = new StytchB2BClient( "project-live-c60c0abe-c25a-4472-a9ed-320c6667d317", "secret-live-80JASucyk7z_G8Z-7dVwZVGXL5NT_qGAQ2I=" ); ``` -------------------------------- ### Stytch B2B SSO: Create SAML & OIDC Connections (Kotlin) Source: https://context7.com/stytchauth/stytch-java/llms.txt Demonstrates how to create both SAML and OIDC SSO connections for an organization using the Stytch Java SDK. It shows the necessary parameters for each connection type and how to handle the results. ```kotlin import com.stytch.java.b2b.models.sso.SSO.* // Create SAML connection val samlResult = client.sso.saml.createConnection( CreateConnectionRequest( organizationId = "organization-test-07971b06-ac8b-4cdb-9c15-63b17e653931", displayName = "Okta SSO" ) ) when (samlResult) { is StytchResult.Success -> { println("Connection ID: ${samlResult.value.connection.connectionId}") println("ACS URL: ${samlResult.value.connection.acsUrl}") println("Audience URI: ${samlResult.value.connection.audienceUri}") } is StytchResult.Error -> println("Failed to create SAML connection") } // Create OIDC connection val oidcResult = client.sso.oidc.createConnection( CreateConnectionRequest( organizationId = "organization-test-07971b06-ac8b-4cdb-9c15-63b17e653931", displayName = "Azure AD" ) ) when (oidcResult) { is StytchResult.Success -> { println("Connection ID: ${oidcResult.value.connection.connectionId}") println("Redirect URL: ${oidcResult.value.connection.redirectUrl}") println("Client ID: ${oidcResult.value.connection.clientId}") println("Client Secret: ${oidcResult.value.connection.clientSecret}") } is StytchResult.Error -> println("Failed to create OIDC connection") } ``` -------------------------------- ### OAuth Authentication with Google, Microsoft, Apple (Kotlin) Source: https://context7.com/stytchauth/stytch-java/llms.txt Demonstrates how to attach an OAuth provider to an existing user and authenticate an OAuth token after a callback. This involves generating an OAuth URL for the user to visit and then processing the token received from the provider. Supported providers include google, microsoft, apple, facebook, github, gitlab, and linkedin. ```kotlin import com.stytch.java.consumer.models.oauth.OAuth.* // Attach OAuth provider to existing user val attachResult = client.oauth.attach( AttachRequest( userId = "user-test-16d9ba61-97a1-4ba4-9720-b03761dc50c6", provider = "google", // Supported providers: google, microsoft, apple, facebook, github, gitlab, linkedin codeChallenge = "challenge_string", codeChallengeMethod = "S256" ) ) when (attachResult) { is StytchResult.Success -> { println("OAuth URL: ${attachResult.value.oauthUrl}") // Redirect user to oauthUrl } is StytchResult.Error -> println("Failed to attach OAuth") } // Authenticate OAuth token after callback val authResult = client.oauth.authenticate( AuthenticateRequest( token = "oauth_token_from_callback_url", sessionDurationMinutes = 60, sessionCustomClaims = mapOf( "oauth_provider" to "google", "verified_email" to true ), codeVerifier = "verifier_string" ) ) when (authResult) { is StytchResult.Success -> { val response = authResult.value println("User ID: ${response.userId}") println("Provider type: ${response.providerType}") println("OAuth user info: ${response.providerValues}") println("Session JWT: ${response.sessionJwt}") } is StytchResult.Error -> println("OAuth authentication failed") } ``` -------------------------------- ### Create Organization in Kotlin and Java Source: https://github.com/stytchauth/stytch-java/blob/main/README.md Shows how to create a new organization within Stytch, specifying its name, a unique slug, and allowed email domains. Handles success and error responses. ```kotlin when (val result = client.organizations.create(CreateRequest( organizationName = "Acme Co", organizationSlug = "acme-co", emailAllowedDomains = listOf("acme.co"), ))) { is StytchResult.Success -> println(result.value) is StytchResult.Error -> println(result.exception) } ``` ```java var emailAllowedDomains = new ArrayList(); emailAllowedDomains.add("acme.co"); CreateRequest request = new CreateRequest( "Acme Co", "acme-co", emailAllowedDomains ); StytchResult response = client.organizations.createCompletable(request).get(); if (response instanceof StytchResult.Error) { var exception = ((StytchResult.Error) response).getException(); System.out.println(exception.getReason()); } else { System.out.println(((StytchResult.Success) response).getValue()); } ``` -------------------------------- ### Log User In or Sign Up via Email Magic Link in Kotlin and Java Source: https://github.com/stytchauth/stytch-java/blob/main/README.md Enables users to log in or sign up for an organization using an email magic link. Requires organization ID, email address, and redirect URLs for login and signup. Includes error handling. ```kotlin when (val result = client.magicLinks.email.loginOrSignup(LoginOrSignupRequest( organizationId = "organization-id-from-create-response-..", emailAddress = "admin@acme.co", loginRedirectURL = "https://example.com/authenticate", signupRedirectURL = "https://example.com/authenticate", )) { is StytchResult.Success -> println(result.value) is StytchResult.Error -> println(result.exception) } ``` ```java LoginOrSignupRequest request = new LoginOrSignupRequest( "organization-id-from-create-response-..", "admin@acme.co", "https://example.com/authenticate", "https://example.com/authenticate" ); StytchResult response = client.magicLinks.getEmail().loginOrSignup(request).get(); if (response instanceof StytchResult.Error) { var exception = ((StytchResult.Error) response).getException(); System.out.println(exception.getReason()); } else { System.out.println(((StytchResult.Success) response).getValue()); } ``` -------------------------------- ### Send Magic Link for Login/Signup (Kotlin/Java) Source: https://context7.com/stytchauth/stytch-java/llms.txt This snippet demonstrates sending a magic link email for passwordless login or signup using the Stytch Consumer SDK. It includes parameters for email, magic link URLs, expiration, and template IDs. Error handling for StytchResult is also shown. ```kotlin import com.stytch.java.consumer.models.magiclinks.MagicLinks.* val result = client.magicLinks.email.loginOrCreate( LoginOrCreateRequest( email = "user@example.com", loginMagicLinkURL = "https://example.com/authenticate?type=login", signupMagicLinkURL = "https://example.com/authenticate?type=signup", expirationMinutes = 30, signupTemplateId = "welcome-template-id", loginTemplateId = "login-template-id" ) ) when (result) { is StytchResult.Success -> { println("Email sent to: ${result.value.email}") println("User ID: ${result.value.userId}") println("Request ID: ${result.value.requestId}") } is StytchResult.Error -> { val exception = result.exception println("Error: ${exception.reason}") } } ``` ```java import com.stytch.java.consumer.models.magiclinks.MagicLinks.LoginOrCreateRequest; import com.stytch.java.core.StytchResult; import com.stytch.java.consumer.models.magiclinks.MagicLinks.LoginOrCreateResponse; LoginOrCreateRequest request = new LoginOrCreateRequest( "user@example.com", "https://example.com/authenticate?type=signup", "https://example.com/authenticate?type=login" ); StytchResult response = client.magicLinks.getEmail().loginOrCreateCompletable(request).get(); if (response instanceof StytchResult.Success) { LoginOrCreateResponse successResponse = ((StytchResult.Success) response).getValue(); System.out.println("Email sent to: " + successResponse.email); System.out.println("User ID: " + successResponse.userId); System.out.println("Request ID: " + successResponse.requestId); } else if (response instanceof StytchResult.Error) { StytchException exception = ((StytchResult.Error) response).exception; System.err.println("Error: " + exception.getReason()); } ``` -------------------------------- ### Stytch Java SDK: Create User Source: https://context7.com/stytchauth/stytch-java/llms.txt Creates a new user in Stytch with the provided details. This includes email, name, phone number, and optional trusted/untrusted metadata. The `createUserAsPending` flag determines if the user is created in a pending state. ```kotlin import com.stytch.java.consumer.models.users.Users.* // Create new user val createResult = client.users.create( CreateRequest( email = "jane.doe@example.com", name = Name( firstName = "Jane", middleName = "Marie", lastName = "Doe" ), phoneNumber = "+14155552671", createUserAsPending = false, trustedMetadata = mapOf( "employee_id" to "EMP001", "department" to "Engineering", "clearance_level" to 3 ), untrustedMetadata = mapOf( "preferences" to mapOf( "theme" to "dark", "notifications" to true ) ) ) ) ``` -------------------------------- ### Create Stytch Client in Kotlin and Java Source: https://github.com/stytchauth/stytch-java/blob/main/README.md Demonstrates the creation of a Stytch client instance using provided project and secret keys. Supports both Kotlin and Java languages. ```kotlin import com.stytch.java.consumer.StytchClient val client = StytchClient( projectId = "project-live-c60c0abe-c25a-4472-a9ed-320c6667d317", secret = "secret-live-80JASucyk7z_G8Z-7dVwZVGXL5NT_qGAQ2I=" ) ``` ```java import com.stytch.java.consumer.StytchClient; StytchClient client = new StytchClient( "project-live-c60c0abe-c25a-4472-a9ed-320c6667d317", "secret-live-80JASucyk7z_G8Z-7dVwZVGXL5NT_qGAQ2I=" ); ``` -------------------------------- ### Manage B2B Members with Stytch Java SDK Source: https://context7.com/stytchauth/stytch-java/llms.txt This snippet illustrates how to manage members within B2B organizations using the Stytch Java SDK. It covers creating, retrieving, updating, deleting, and reactivating members. Ensure the Stytch client and organization ID are properly initialized. ```kotlin import com.stytch.java.b2b.models.organizationsmembers.OrganizationsMembers.* // Create member val createResult = client.organizations.members.create( CreateRequest( organizationId = "organization-test-07971b06-ac8b-4cdb-9c15-63b17e653931", emailAddress = "john.doe@acme.com", name = "John Doe", isBreakglass = false, mfaEnrolled = false, mfaPhoneNumber = "+14155552671", untrustedMetadata = mapOf( "department" to "Engineering", "title" to "Senior Developer" ), createMemberAsPending = false, roles = listOf("admin", "developer") ) ) when (createResult) { is StytchResult.Success -> { val member = createResult.value.member println("Member created: ${member.memberId}") println("Email: ${member.emailAddress}") println("Status: ${member.status}") } is StytchResult.Error -> println("Failed to create member") } // Get member val getResult = client.organizations.members.get( GetRequest( organizationId = "organization-test-07971b06-ac8b-4cdb-9c15-63b17e653931", memberId = "member-test-32d097bc-8c04-4c39-913f-e0c51c6dce1b" ) ) // Update member val updateResult = client.organizations.members.update( UpdateRequest( organizationId = "organization-test-07971b06-ac8b-4cdb-9c15-63b17e653931", memberId = "member-test-32d097bc-8c04-4c39-913f-e0c51c6dce1b", name = "John Smith", emailAddress = "john.smith@acme.com", isBreakglass = false, mfaEnrolled = true, mfaPhoneNumber = "+14155559999", untrustedMetadata = mapOf("title" to "Lead Developer") ) ) // Delete member val deleteResult = client.organizations.members.delete( DeleteRequest( organizationId = "organization-test-07971b06-ac8b-4cdb-9c15-63b17e653931", memberId = "member-test-32d097bc-8c04-4c39-913f-e0c51c6dce1b" ) ) // Reactivate member val reactivateResult = client.organizations.members.reactivate( ReactivateRequest( organizationId = "organization-test-07971b06-ac8b-4cdb-9c15-63b17e653931", memberId = "member-test-32d097bc-8c04-4c39-913f-e0c51c6dce1b" ) ) ```