### Go Full Example Setup Source: https://stytch.com/docs/llms-full.txt A complete Go HTTP server setup demonstrating Stytch integration for magic link authentication. ```go package main import ( "bytes" "encoding/json" "net/http" "os" ) func main() { http.HandleFunc("/login", sendLoginHandler) http.HandleFunc("/authenticate", authenticateHandler) http.HandleFunc("/dashboard", dashboardHandler) http.ListenAndServe(":3000", nil) } // Implement sendLoginHandler/authenticateHandler/dashboardHandler using the // requests shown above. ``` -------------------------------- ### Full Stytch B2B Authentication Example Source: https://stytch.com/docs/multi-tenant-auth/build-auth/custom/via-api A complete example demonstrating the setup and usage of Stytch B2B authentication, including API client instantiation, environment variable loading, and HTTP handler registration. ```go package main import ( "context" "fmt" "log" "net/http" "os" gorillaSessions "github.com/gorilla/sessions" "github.com/joho/godotenv" "github.com/stytchauth/stytch-go/v15/stytch/b2b/b2bstytchapi" "github.com/stytchauth/stytch-go/v15/stytch/b2b/discovery/intermediatesessions" discoveryOrgs "github.com/stytchauth/stytch-go/v15/stytch/b2b/discovery/organizations" "github.com/stytchauth/stytch-go/v15/stytch/b2b/magiclinks/discovery" emlDiscovery "github.com/stytchauth/stytch-go/v15/stytch/b2b/magiclinks/email/discovery" "github.com/stytchauth/stytch-go/v15/stytch/b2b/organizations" "github.com/stytchauth/stytch-go/v15/stytch/b2b/sessions" ) var ctx = context.Background() const sessionKey = "stytch_session_token" func main() { // Load variables from .env file into the environment. if err := godotenv.Load(".env.local"); err != nil { log.Fatalf("Error loading .env file: %v", err) } // Instantiate a new API service. service := NewAuthService( os.Getenv("STYTCH_PROJECT_ID"), os.Getenv("STYTCH_SECRET"), ) // Register HTTP handlers. mux := http.NewServeMux() mux.HandleFunc("/", service.indexHandler) mux.HandleFunc("/login", service.sendMagicLinkHandler) ``` -------------------------------- ### Go: Full Application Setup Example Source: https://stytch.com/docs/consumer-auth/build-auth/custom/via-api This is a basic structure for a Go application demonstrating how to set up HTTP handlers for login, authentication, and protected dashboard routes. ```Go package main import ( "bytes" "encoding/json" "net/http" "os" ) func main() { http.HandleFunc("/login", sendLoginHandler) http.HandleFunc("/authenticate", authenticateHandler) http.HandleFunc("/dashboard", dashboardHandler) http.ListenAndServe(":3000", nil) } // Implement sendLoginHandler/authenticateHandler/dashboardHandler using the // requests shown above. ``` -------------------------------- ### OAuth Google Start Source: https://stytch.com/docs/api-reference/consumer/frontend-sdks/vanilla-js/methods/oauth/start Starts the OAuth flow for Google. This example demonstrates how to configure redirect URLs, custom scopes, and provider parameters. ```APIDOC ## oauth.google.start() ### Description Starts the OAuth flow for Google by redirecting the browser to Stytch's OAuth start endpoint. It automatically generates and stores a PKCE `code_verifier`. ### Method `stytch.oauth.google.start(options)` ### Parameters #### Request Body - **login_redirect_url** (string) - Required - The URL Stytch redirects to after the OAuth flow is completed for an existing user. Must be configured as a Login URL in the Redirect URL page. - **signup_redirect_url** (string) - Required - The URL Stytch redirects to after the OAuth flow is completed for a new user. Must be configured as a Signup URL in the Redirect URL page. - **custom_scopes** (string[]) - Optional - A list of custom scopes to include. These must be URL encoded. - **provider_params** (object) - Optional - An object containing parameters to pass to the OAuth provider (e.g., `login_hint`). Consult the OAuth provider's documentation for supported parameters. - **oauth_attach_token** (string) - Optional - A single-use token for connecting Stytch User selection from an OAuth Attach request to the corresponding OAuth Start request. ### Request Example ```javascript import { StytchClient } from '@stytch/vanilla-js'; const stytch = new StytchClient('YOUR_PUBLIC_TOKEN'); stytch.oauth.google.start({ login_redirect_url: 'YOUR_APP_URL/authenticate', signup_redirect_url: 'YOUR_APP_URL/authenticate', custom_scopes: [ 'https://www.googleapis.com/auth/documents.readonly', 'https://www.googleapis.com/auth/drive.readonly', ], provider_params: { login_hint: 'example_hint@stytch.com', }, }); ``` ### Response This method initiates a browser redirect and does not return a response directly in the SDK. The outcome of the OAuth flow is handled at the `redirect_url`. ``` -------------------------------- ### Full Completed Example: Node.js Stytch Integration Source: https://stytch.com/docs/llms-full.txt A complete Node.js example demonstrating Stytch email magic link authentication, including Express setup, login, authentication callback, and session protection. ```javascript const express = require('express'); const session = require('express-session'); const stytch = require('stytch'); const app = express(); app.use(express.json()); app.use(session({ resave: true, saveUninitialized: false, secret: 'session-signing-secret', })); const stytchClient = new stytch.Client({ project_id: process.env.STYTCH_PROJECT_ID, secret: process.env.STYTCH_SECRET, }); app.post('/login', async (req, res) => { const params = { email: req.body.email, login_magic_link_url: "http://localhost:3000/authenticate", signup_magic_link_url: "http://localhost:3000/authenticate", }; const resp = await stytchClient.magicLinks.email.loginOrCreate(params); res.json(resp); }); ``` -------------------------------- ### Initialize Stytch Client and Login Route Source: https://stytch.com/docs/multi-tenant-auth/build-auth/custom/via-api Initialize the Stytch client using environment variables and set up a Flask route for the login/signup flow. This example demonstrates basic setup for handling user email input. ```python import os import dotenv from flask import Flask, request, redirect, session, url_for from stytch import B2BClient from stytch.core.response_base import StytchError # load the .env file dotenv.load_dotenv() ``` -------------------------------- ### Install Next.js Package Source: https://stytch.com/docs/api-reference/consumer/frontend-sdks/nextjs/installation Install the Stytch Next.js package using npm. ```bash npm install @stytch/nextjs ``` -------------------------------- ### Install Stytch Next.js SDK Source: https://stytch.com/docs/consumer-auth/authentication/otps/sdk Install the Stytch Next.js SDK using npm or yarn. ```bash npm install @stytch/nextjs ``` ```bash yarn add @stytch/nextjs ``` -------------------------------- ### Install Stytch Vanilla JS SDK Source: https://stytch.com/docs/api-reference/consumer/frontend-sdks/vanilla-js/installation Install the `@stytch/vanilla-js` package using npm. ```bash npm install @stytch/vanilla-js ``` -------------------------------- ### Get M2M Client Response Source: https://stytch.com/docs/llms-full.txt Example response from the Get M2M Client endpoint. The `next_client_secret_last_four` field indicates if a rotation is in progress. ```javascript { "m2m_client": { "client_description": "Following the Stytch guide.", "client_id": "m2m-client-test-a50053...", "client_name": "Example client", "client_secret_last_four": "QqNU", "next_client_secret_last_four": null, "scopes": [ "read:settings", "update:settings" ], "status": "active", "trusted_metadata": { "billing_tier": "standard", "api_version": "v2" } }, "request_id": "request-id-test-c50eb06f-69b4-41be-8640-0d9fd2f561ae", "status_code": 200 } ``` -------------------------------- ### Install Stytch Go SDK Source: https://stytch.com/docs/multi-tenant-auth/build-auth/custom/via-api Use this command to install the Stytch Go SDK. Ensure you are using the correct version. ```go go get github.com/stytchauth/stytch-go/v16 ``` -------------------------------- ### Example Response for Get Connected Apps Source: https://stytch.com/docs/api-reference/consumer/frontend-sdks/nextjs/methods/connected-apps/get-connected-apps This is an example of the JSON response structure returned by the `getConnectedApps` method, detailing the properties of a connected application. ```json { "status_code": 200, "request_id": "request-id-test-b05c992f-ebdc-489d-a754-c7e70ba13141", "connected_apps": [ { "client_type": "first_party", "connected_app_id": "connected-app-test-aeadeabc-a3a3-4796-83d0-b757e3001000", "description": "A first party connected app", "logo_url": null, "name": "first-party-confidential-app", "scopes_granted": "openid profile email" } ] } ``` -------------------------------- ### Initialize Stytch Client and Set Up Login Route Source: https://stytch.com/docs/multi-tenant-auth/build-auth/custom/via-api Initializes the Stytch client with project credentials and registers an HTTP handler for the /login route to initiate the magic link flow. ```Go package main import ( "context" "fmt" "log" "net/http" "os" gorillaSessions "github.com/gorilla/sessions" "github.com/joho/godotenv" "github.com/stytchauth/stytch-go/v16/stytch/b2b/b2bstytchapi" discoveryOrgs "github.com/stytchauth/stytch-go/v16/stytch/b2b/discovery/organizations" "github.com/stytchauth/stytch-go/v16/stytch/b2b/magiclinks/discovery" emlDiscovery "github.com/stytchauth/stytch-go/v16/stytch/b2b/magiclinks/email/discovery" ) var ctx = context.Background() const sessionKey = "stytch_session_token" func main() { // Load variables from .env file into the environment. if err := godotenv.Load(".env.local"); err != nil { log.Fatalf("Error loading .env file: %v", err) } // Instantiate a new API service. service := NewAuthService( os.Getenv("STYTCH_PROJECT_ID"), os.Getenv("STYTCH_SECRET"), ) // Register HTTP handlers. mux := http.NewServeMux() mux.HandleFunc("/login", service.sendMagicLinkHandler) // Start server. server := http.Server{ Addr: ":3000", Handler: mux, } log.Println("WARNING: For testing purposes only. Not intended for production use...") log.Println("Starting server on http://localhost:3000") if err := server.ListenAndServe(); err != nil { log.Fatal(err) } } type AuthService struct { client *b2bstytchapi.API store *gorillaSessions.CookieStore } func NewAuthService(projectId, secret string) *AuthService { client, err := b2bstytchapi.NewClient(projectId, secret) if err != nil { log.Fatalf("Error creating client: %v", err) } return &AuthService{ client: client, store: gorillaSessions.NewCookieStore([]byte("your-secret-key")), } } func (s *AuthService) sendMagicLinkHandler(w http.ResponseWriter, r *http.Request) { if err := r.ParseForm(); err != nil { log.Printf("Error parsing form: %v\n", err) http.Error(w, err.Error(), http.StatusInternalServerError) return } email := r.Form.Get("email") if email == "" { http.Error(w, "Email is required", http.StatusBadRequest) return } _, err := s.client.MagicLinks.Email.Discovery.Send( ctx, &emlDiscovery.SendParams{ EmailAddress: email, }) if err != nil { log.Printf("Error sending email: %v\n", err) http.Error(w, err.Error(), http.StatusInternalServerError) return } w.WriteHeader(http.StatusOK) fmt.Fprintln(w, "Successfully sent magic link email!") } ``` -------------------------------- ### Password Reset by Email Start API Response Source: https://stytch.com/docs/api-reference/consumer/frontend-sdks/nextjs/methods/passwords/reset-by-email-start This is an example of a successful response from the Reset By Email Start API endpoint. It includes status codes, request IDs, and user/email identifiers. ```json { "status_code": 200, "request_id": "request-id-test-b05c992f-ebdc-489d-a754-c7e70ba13141", "user_id": "user-test-16d9ba61-97a1-4ba4-9720-b03761dc50c6", "email_id": "email-test-81bf03a8-86e1-4d95-bd44-bb3495224953" } ``` -------------------------------- ### Start WebAuthn Registration with Passkey Options Source: https://stytch.com/docs/consumer-auth/authentication/passkeys/overview Call this endpoint to initiate the WebAuthn registration process and retrieve options for Passkey credential creation. Ensure `return_passkey_credential_options` is set to true. ```bash curl --request POST \ --url https://test.stytch.com/v1/webauthn/register/start \ -u 'PROJECT_ID:SECRET' \ -H 'Content-Type: application/json' \ -d '{ "user_id": "user-test-16d9ba61-97a1-4ba4-9720-b03761dc50c6", "domain": "example.com", "return_passkey_credential_options": true }' ``` -------------------------------- ### Before: Global Static Client Initialization Source: https://stytch.com/docs/api-reference/consumer/mobile-sdks/ios/upgrade-guide Demonstrates the older method of configuring and using a global static Stytch client. ```swift import StytchCore // Configure first (typically in AppDelegate or App.init) StytchClient.configure(configuration: .init(publicToken: "public-token-live-...")) // Then use the global static anywhere let response = try await StytchClient.otps.send(parameters: params) ``` -------------------------------- ### Get Synchronous Session - React SDK Source: https://stytch.com/docs/api-reference/consumer/frontend-sdks/react/methods/sessions/get-session-sync Use the `useStytch` hook to get the `stytch` instance and then call `session.getSync()` to retrieve the cached session object. This example displays the session ID if a session exists, otherwise it indicates no active session. ```javascript import { useStytch } from '@stytch/react'; export const SessionDisplay = () => { const stytch = useStytch(); const session = stytch.session.getSync(); return session ? (

Session ID: {session.session_id}

) : (

No active session

); }; ``` -------------------------------- ### Install Stytch SDK Source: https://stytch.com/docs/consumer-auth/authentication/magic-links/adding-magic-links-to-custom-auth-flow Install the Stytch Node.js SDK using npm. This is the first step to using Stytch's backend authentication features. ```bash npm install stytch ``` -------------------------------- ### cryptoWallets.authenticateStart Source: https://stytch.com/docs/api-reference/consumer/frontend-sdks/vanilla-js/methods/crypto-wallets/authenticate-start Wraps the Crypto Wallet Authenticate Start endpoint. Call this method to prompt the user to sign a challenge using their crypto wallet. For Ethereum crypto wallets, the challenge will follow the Sign In With Ethereum (SIWE) protocol if you have toggled **SIWE Enabled** in the SDK Configuration page. The domain and URI will be inferred automatically, but you may optionally override the URI. Load the challenge data by calling `cryptoWallets.authenticateStart()`. You’ll then pass this challenge to the user’s wallet for signing. You can do so by using the crypto provider’s built-in API and by including the `crypto_wallet_address` and challenge that is provided from `cryptoWallets.authenticateStart()`. See Ethereum’s EIP-1193 for an example of Ethereum’s provider API. ```APIDOC ## cryptoWallets.authenticateStart ### Description Initiates the crypto wallet authentication process by requesting a challenge from Stytch, which the user will sign. ### Method `cryptoWallets.authenticateStart(params)` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **crypto_wallet_type** (string) - Required - The type of wallet to authenticate. Currently `ethereum` and `solana` are supported. Wallets for any EVM-compatible chains (such as Polygon or BSC) are also supported and are grouped under the `ethereum` type. - **crypto_wallet_address** (string) - Required - The crypto wallet address to authenticate. - **siwe_params** (object) - Optional - The parameters for a Sign In With Ethereum (SIWE) message. May only be passed if the `crypto_wallet_type` is `ethereum` and if **SIWE Enabled** is toggled in the Frontend SDK page. - **uri** (string) - Optional - Defaults to `window.location.origin`. An RFC 3986 URI referring to the resource that is the subject of the signing. - **statement** (string) - Optional - A human-readable ASCII assertion that the user will sign. The statement may only include reserved, unreserved, or space characters according to RFC 3986 definitions, and must not contain other forms of whitespace such as newlines, tabs, and carriage returns. - **chain_id** (string) - Optional - The EIP-155 Chain ID to which the session is bound. Defaults to `1`. Must be the string representation of an integer between 1 and 9,223,372,036,854,775,771, inclusive. - **issued_at** (string) - Optional - The time when the message was generated. Defaults to the current time. All timestamps in our API conform to the RFC 3339 standard and are expressed in UTC, e.g. `2021-12-29T12:33:09Z`. - **not_before** (string) - Optional - The time when the signed authentication message will become valid. Defaults to the current time. All timestamps in our API conform to the RFC 3339 standard and are expressed in UTC, e.g. `2021-12-29T12:33:09Z`. - **message_request_id** (string) - Optional - A system-specific identifier that may be used to uniquely refer to the sign-in request. The `message_request_id` must be a valid pchar according to RFC 3986 definitions. - **resources** (array[string]) - Optional - A list of information or references to information the user wishes to have resolved as part of authentication. Every resource must be an RFC 3986 URI. ### Request Example ```javascript const { challenge } = await stytch.cryptoWallets.authenticateStart({ crypto_wallet_address: "0x1234567890abcdef1234567890abcdef12345678", crypto_wallet_type: "ethereum", siwe_params: { statement: "Please sign this message to confirm your identity.", uri: "https://example.com", chain_id: "1", issued_at: "2023-01-01T12:00:00Z", not_before: "2023-01-01T12:05:00Z", message_request_id: "my-unique-request-id", resources: ["https://example.com/resource1", "https://example.com/resource2"] } }); ``` ### Response #### Success Response (200) - **challenge** (string) - The challenge string that needs to be signed by the user's crypto wallet. - **request_id** (string) - The unique identifier for the request. #### Response Example ```json { "challenge": "Signing in with Project: 7_EPetPqfdEiDCJtgad6-xsXytN3Ee9tx6mdRTQK3fC7-J2PDxpP1GAvYB9Ic4E09h-K88STiRIzKSGP", "request_id": "request-id-test-b05c992f-ebdc-489d-a754-c7e70ba13141", "status_code": 200 } ``` ``` -------------------------------- ### Get Ethereum Address from MetaMask Source: https://stytch.com/docs/consumer-auth/authentication/crypto-wallets/api Fetches the user's MetaMask Ethereum address. Ensure `window.ethereum` is defined, indicating MetaMask is installed. ```javascript const [address] = await window.ethereum.request({ method: 'eth_requestAccounts' }); ``` -------------------------------- ### Initialize Stytch B2B SDK and Provider Source: https://stytch.com/docs/api-reference/consumer/mobile-sdks/react-native/quickstart Import necessary components, create a Stytch client configuration with your public token, and wrap your application with the StytchB2BProvider. ```javascript import { createStytchB2B, StytchClientConfiguration, StytchB2BProvider, useStytchB2B, useStytchMember, useStytchMemberSession, useStytchOrganization, useStytchB2BAuthenticationState, } from '@stytch/react-native-b2b'; import { B2BAuthenticationState } from '@stytch/react-native-b2b'; const stytch = createStytchB2B( new StytchClientConfiguration('public-token-live-...') ); function App() { return ( ); } function MemberDisplay() { const member = useStytchMember(); // ApiOrganizationV1Member | undefined const memberSession = useStytchMemberSession(); // ApiB2bSessionV1MemberSession | undefined const organization = useStytchOrganization(); // ApiOrganizationV1Organization | undefined const authState = useStytchB2BAuthenticationState(); if (authState instanceof B2BAuthenticationState.Authenticated) { return {authState.member.emailAddress} — {authState.organization?.organizationName}; } return null; } ``` -------------------------------- ### Start and Complete WebAuthn Authentication Source: https://stytch.com/docs/llms-full.txt Initiates the WebAuthn authentication process by calling the API to get request options, then uses the browser's WebAuthn API to get a credential, serializes it, and sends it back to the server for verification. Ensure the necessary serialization functions are available. ```javascript // Authentication const webAuthnAuthenticateStartResponse = await callWebauthnAuthenticateStart(); const options = webAuthnAuthenticateStartResponse.public_key_credential_request_options; const publicKey = PublicKeyCredential.parseRequestOptionsFromJSON(JSON.parse(options)); const credential = (await navigator.credentials.get({publicKey})) as PublicKeyCredential; const serializedCredential = serializeAssertionCredential( credential as PublicKeyCredential, ); await callWebauthnAuthenticate(JSON.stringify(serializedCredential)) .then(resp => { /* User has successfully authenticated */ }) .catch(err => { /* Authentication error */ }); ``` -------------------------------- ### Stytch API Response for Authentication Start Source: https://stytch.com/docs/api-reference/consumer/frontend-sdks/nextjs/methods/crypto-wallets/authenticate-start This is an example of the JSON response received from the Stytch API after successfully calling the `cryptoWallets.authenticateStart` method for an Ethereum wallet. ```json { "challenge": "Signing in with Project: 7_EPetPqfdEiDCJtgad6-xsXytN3Ee9tx6mdRTQK3fC7-J2PDxpP1GAvYB9Ic4E09h-K88STiRIzKSGP", "request_id": "request-id-test-b05c992f-ebdc-489d-a754-c7e70ba13141", "status_code": 200 } ``` -------------------------------- ### Initialize Stytch Java B2B Client Source: https://stytch.com/docs/multi-tenant-auth/build-auth/custom/via-api Example of how to create an instance of the Stytch B2B client in Java, using your project ID and secret key. ```java import com.stytch.java.b2b.StytchB2BClient val client = StytchB2BClient( projectId = "YOUR_PROJECT_ID", secret = "YOUR_SECRET_KEY" ) ``` -------------------------------- ### Install Stytch Vanilla JS SDK Source: https://stytch.com/docs/consumer-auth/authentication/passkeys/login-sdk Install the Stytch frontend SDK locally via npm or yarn. This is the first step for integrating Passkeys. ```bash npm install @stytch/vanilla-js --save ``` -------------------------------- ### Full Completed Stytch Node.js Example Source: https://stytch.com/docs/consumer-auth/build-auth/custom/via-api A complete example demonstrating the integration of Stytch for authentication, including initialization, login, authentication callback, and session-protected routes. ```javascript const express = require('express'); const session = require('express-session'); const stytch = require('stytch'); const app = express(); app.use(express.json()); app.use(session({ resave: true, saveUninitialized: false, secret: 'session-signing-secret', })); const stytchClient = new stytch.Client({ project_id: process.env.STYTCH_PROJECT_ID, secret: process.env.STYTCH_SECRET, }); app.post('/login', async (req, res) => { const params = { email: req.body.email, login_magic_link_url: "http://localhost:3000/authenticate", signup_magic_link_url: "http://localhost:3000/authenticate", }; const resp = await stytchClient.magicLinks.email.loginOrCreate(params); res.json(resp); }); app.get('/authenticate', async (req, res) => { const token = req.query.token; const resp = await stytchClient.magicLinks.authenticate({ token, session_duration_minutes: 60, }); req.session.session_jwt = resp.session_jwt; res.redirect('/dashboard'); }); app.get('/dashboard', async (req, res) => { const sessionJWT = req.session.session_jwt; if (!sessionJWT) { res.send("Log in to view this page"); return; } const resp = await stytchClient.sessions.authenticate({ session_jwt: sessionJWT, }); if (resp.status_code !== 200) { req.session.session_jwt = undefined; res.send("Log in to view this page"); return; } res.send("You're logged in."); }); app.listen(3000, () => console.log('Server running on http://localhost:3000')); ``` -------------------------------- ### Full Stytch B2B Flask App Example Source: https://stytch.com/docs/llms-full.txt A complete Flask application demonstrating Stytch B2B integration. Includes setup, login, authentication, and session management. ```python import os import dotenv from flask import Flask, request, redirect, session, url_for from stytch import B2BClient from stytch.core.response_base import StytchError # load the .env file dotenv.load_dotenv() # Load stytch client stytch_client = B2BClient( project_id=os.getenv("STYTCH_PROJECT_ID"), secret=os.getenv("STYTCH_SECRET"), environment="test" ) app = Flask(__name__) app.secret_key = 'some-secret-key' @app.route('/login', methods=['POST']) def login(): data = request.get_json() email = data.get("email", None) if not email: return "Email required" try: stytch_client.magic_links.email.discovery.send( email_address=email ) except StytchError as e: return e.details.original_json return "Success! Check your email" @app.route('/authenticate', methods=['GET']) def authenticate(): token = request.args.get('token', None) token_type = request.args.get('stytch_token_type', None) # Distinct token_type for each auth flow # so you know which authenticate() method to use if token_type != 'discovery': return f"token_type: {token_type} not supported" try: resp = stytch_client.magic_links.discovery.authenticate( discovery_magic_links_token=token, ) except StytchError as e: return e.details.original_json ist = resp.intermediate_session_token discovered_orgs = resp.discovered_organizations if len(discovered_orgs): # email belongs to >= 1 organization, log into the first one try: ``` -------------------------------- ### Get OpenID Configuration with Custom Domain Source: https://stytch.com/docs/connected-apps/resources/custom-domains This example shows how to fetch the OpenID Connect discovery document using a custom domain. The endpoints within this document will be prefixed with your custom domain. ```APIDOC ## GET /.well-known/openid-configuration ### Description Retrieves the OpenID Connect discovery document for the Stytch service, using a custom domain. ### Method GET ### Endpoint https://login.yourcompany.com/.well-known/openid-configuration ### Response #### Success Response (200) - **registration_endpoint** (string) - The endpoint for OIDC registration. - **token_endpoint** (string) - The endpoint for token exchange. - **userinfo_endpoint** (string) - The endpoint for retrieving user information. #### Response Example ```json { "registration_endpoint": "https://login.yourcompany.com/v1/oauth2/register", "token_endpoint": "https://login.yourcompany.com/v1/oauth2/token", "userinfo_endpoint": "https://login.yourcompany.com/v1/oauth2/userinfo", "jwks_uri": "https://login.yourcompany.com/v1/jwks", "issuer": "https://login.yourcompany.com", "response_types_supported": ["code"], "subject_types_supported": ["public"], "id_token_signing_alg_values_supported": ["RS256"], "scopes_supported": ["openid", "email", "profile"], "claims_supported": ["aud", "exp", "iat", "iss", "sub", "email", "email_verified", "name", "given_name", "family_name"] } ``` ``` -------------------------------- ### Node.js Server Setup Source: https://stytch.com/docs/llms-full.txt Basic Express.js server setup with Stytch integration for magic link authentication. ```javascript app.listen(3000, () => console.log('Server running on http://localhost:3000')); ``` ``` -------------------------------- ### Initialize StytchB2BSDK Source: https://stytch.com/docs/api-reference/consumer/mobile-sdks/ios/upgrade-guide Shows how to import and initialize the StytchB2B SDK with a public token, following the migration pattern from the old SDK. ```swift import StytchB2BSDK let stytch = createStytchB2B( configuration: .init(publicToken: "public-token-live-...") ) ``` -------------------------------- ### Get Active Session with useStytchSession Source: https://stytch.com/docs/api-reference/consumer/mobile-sdks/react-native/hooks/use-stytch-session Use the useStytchSession hook to fetch the active session for the currently signed-in user. If no user is authenticated, it returns null. Ensure you have installed the '@stytch/react-native-consumer' package. ```javascript import { Text } from 'react-native'; import { useStytchSession } from '@stytch/react-native-consumer'; export const SessionInfo = () => { const session = useStytchSession(); return session ? Session ID: {session.session_id} : No active session; }; ``` -------------------------------- ### Auth0 OAuth Integration Source: https://stytch.com/docs/llms-full.txt Example of integrating Stytch OAuth with Auth0. It uses Auth0Client to get ID token claims and passes the raw token to OAuthAuthorizeComponent. Includes redirection to login on error. ```javascript import { useState, useEffect } from 'react'; import { Auth0Client } from '@auth0/auth0-spa-js'; import { OAuthAuthorizeComponent } from './components'; const auth0 = new Auth0Client({ domain: '{yourDomain}', clientId: '{yourClientId}' }); export default function OAuthAuthorizePage() { const [token, setToken] = useState(null) useEffect(() => { auth0.getIdTokenClaims() then((claims) => setToken(claims.__raw)) // Redirect to your login page if the user is not logged in .catch(err => redirectToLogin(window.location.href)) }, []); return session ? : null; } ``` -------------------------------- ### Stytch UI Overview Source: https://stytch.com/docs/llms-full.txt Guides for integrating Stytch UI components for login and signup flows. Configure authentication methods and customize styling for a production-ready login experience. ```Markdown ## Get started Step-by-step guide to add Stytch UI to your app. Theme and customize the pre-built UI components. Full UI config reference for Stytch Login. Explore sample implementations. Stytch SDKs and UI are hosted by your application. ``` -------------------------------- ### LUDS Password Strength Check Response Source: https://stytch.com/docs/consumer-auth/authentication/passwords/strength-policy Example response from the Strength check endpoint when using the LUDS password strength policy. Use the feedback on missing characters and complexity to guide users. ```json { "breach_detection_on_create": true, "breached_password": false, "feedback": { "luds_requirements": { "has_digit": true, "has_lower_case": true, "has_symbol": true, "has_upper_case": true, "missing_characters": 2, "missing_complexity": 0 }, "suggestions": null, "warning": null }, "request_id": "request-id-test-86779128-d4e7-4dd4-a588-88faa570f638", "score": 0, "status_code": 200, "strength_policy": "luds", "valid_password": false } ``` -------------------------------- ### B2B OAuth Authorization Entry Point (Node.js) Source: https://stytch.com/docs/llms-full.txt Node.js Express example for initiating the Stytch B2B OAuth authorization flow. It handles request parameters, starts the authorization, and manages consent or redirection. ```javascript const express = require('express'); const cookieParser = require('cookie-parser'); const stytch = require('stytch'); const app = express(); app.use(cookieParser()); app.use(express.urlencoded({ extended: false })); const client = new stytch.B2BClient({ project_id: process.env.STYTCH_PROJECT_ID, secret: process.env.STYTCH_SECRET, }); async function performAuthorize(params) { return client.idp.oauth.authorize(params); } app.get('/oauth/authorize', async (req, res) => { try { const { response_type = 'code', scope = '', client_id, redirect_uri, state, code_challenge, code_challenge_method, } = req.query; const scopes = String(scope).split(' ').filter(Boolean); const session_jwt = req.cookies?.stytch_session_jwt || undefined; const baseParams = { client_id, redirect_uri, response_type, scopes, state, code_challenge, code_challenge_method, session_jwt, }; const startResp = await client.idp.oauth.authorizeStart(baseParams); if (startResp.consent_required) { // See Step 2: Render consent screen return res.status(200).send('Consent required'); } const authResp = await performAuthorize({ consent_granted: true, ...baseParams, }); res.status(307).set('Location', authResp.redirect_uri).send(); } catch (err) { console.error(err); res.status(400).send('Authorization failed'); } }); app.listen(3000, () => console.log('Server listening on :3000')); ```