> ## Documentation Index
> Fetch the complete documentation index at: https://stytch.com/docs/llms.txt
> Use this file to discover all available pages before exploring further.

# Additional migration considerations

> Deploying a new authentication service is not always limited to just changing login and signup logic.

export const idp = "Identity provider; a worksforce application that allows companies to centrally manage their employees’ identity information as well as their access to company resources and applications.";

export const member = "Represents an individual end user's account within a given Organization, uniquely identified within that Organization by their email address.";

<Tabs>
  <Tab title="Consumer auth">
    Deploying a new authentication service is not always limited to just changing login and signup logic. If your backend reads session and user data or listens to auth related events, you may need to refactor this logic to point to Stytch's APIs.

    ## Ingesting events and managing visibility

    If your legacy auth provider requires you to set up log streams or webhooks for event visibility, here are a few examples of how to move that logic to Stytch.

    With Stytch, there are multiple ways to gain access to authentication-related logs.

    ### Option 1: Use webhooks

    You can enroll in webhooks through the Stytch Dashboard by specifying URL(s) at which you wish to receive the webhook POST requests and the type of events you wish to receive.

    Check out our [webhooks guide](/api-reference/consumer/api/overview) to learn how to keep your internal database records in sync with any changes that occur in Stytch's Consumer Authentication API.

    ```js theme={null}
    // Example user create via dashboard (dashboard.user.create)
    {
        "project_id": "project-live-123-...",
        "event_id": "event-live-123-...",
        "action": "CREATE",
        "object_type": "user",
        "source": "DASHBOARD",
        "id": "user-live-123...",
        "timestamp": "2024-11-21T06:47:49.555247073Z",
        "user": { ... }
    }

    // Example update user event via API or SDK call (direct.user.update)
    {
        "project_id": "project-live-123-...",
        "event_id": "event-live-123-...",
        "action": "UPDATE",
        "object_type": "user",
        "source": "DIRECT",
        "id": "user-live-123...",
        "timestamp": "2024-11-21T06:47:49.555247073Z",
        "user": { ... }
    }
    ```

    ### Option 2: Log calls and responses made to Stytch from within your own application

    Frontend SDK example, using email magic links with JS:

    ```js theme={null}
    const onSubmit: FormEventHandler = async (e) => {
        if (isValidEmail(email)) {
          const resp = await stytchClient.magicLinks.email.send(email);

          // Send the response of the call to your logging tool
          // This includes the user info and response code

          if (resp.status === 200) {
            Bugsnag.notify(resp);
            setEMLSent(STATUS.SENT);
          } else {
            Bugsnag.notify(e);
            setEMLSent(STATUS.ERROR);
          }
        }
      };
    ```

    Backend SDK/API example, using Python:

    ```python theme={null}
    @app.route("/login_or_create_user", methods=["POST"])
      def login_or_create_user() -> str:
          resp = stytch_client.magic_links.email.login_or_create(
              email=request.form["email"],
              login_magic_link_url=MAGIC_LINK_URL,
              signup_magic_link_url=MAGIC_LINK_URL,
          )
          # Send the response of the call to your logging tool
          # This includes the user info and response code

          if resp.status_code == 200:
            bugsnag.notify(resp)

          if resp.status_code != 200:
              bugsnag.notify(resp)
              print(resp)
              return "something went wrong sending magic link"

          return render_template("emailSent.html")
    ```

    ### Option 3: Check out the event logs in the dashboard

    From the Activity section in the Dashboard, you can view the [Event Logs](https://stytch.com/dashboard/activity) to debug your authentication flows.

    ## Pre-production testing

    If you run any automated or pre-production testing that includes authentication, here are a few best practices to move that to Stytch:

    * If you have multiple pre-production environments that need their own user bases, use the Stytch Dashboard to create multiple test environments and have each set of test keys map to each of your internal environments.
    * Stytch supports [sandbox values](/consumer-auth/testing/sandbox-values) to use for most primary login factors. Check out our [E2E Testing resource](/consumer-auth/testing/e2e-testing) for additional information.

    ## Reconciling deduplication

    Stytch uses email or phone number as a primary key for identifying users. This means if you are using a combination of the Stytch Email Magic Links product and OAuth Logins then Stytch will automatically deduplicate users with matching email addresses. For example, if you create a user via Email Magic Links using the email address [example@stytch.com](mailto:example@stytch.com), and then later login with a Google account which is tied to [example@stytch.com](mailto:example@stytch.com), Stytch will treat these as the same user with the same `user_id`.

    For this reason, you may need to merge your users' accounts before migrating to Stytch. If your script attempts to manually create two users in Stytch with the same email address, you will receive a `duplicate_email` error.

    ## Linking Stytch users back to your DB

    You should continue to maintain your own internal user table in your application, and link Stytch's `user_id` in as a column in your table. You can also add your internal reference of the user as a `trusted_metadata` field on the Stytch user.

    ## Migrating over additional user data

    Our `trusted_metadata` supports nested JSON and can be used to migrate and store any additional user data.

    We recommend to keep this data limited to information that is required in the context of authentication, for example: user role or other claims.

    **Keeping identifiers consistent**: If you have analytics or other internal processes that key off of your internal user ID reference, and would like these IDs to stay consistent, we recommend to add your internal user ID as `trusted_metadata`. Your backend should then default to reading ID from this value, but fall back to the Stytch `user_id` if it does not exist. Stytch does not currently support seeding user GUIDs.

    ## Email/phone verification status

    Stytch manages the email and phone verification status of users. When a user is created in Stytch, it will have an `email.verified` or `phone.verified` value of `false` until the user completes their first login that verifies ownership of that account (for example an email OTP, SMS OTP flow or OAuth login).

    See more information in our guides [here](/consumer-auth/authentication/passwords/email-verification/overview).

    If you have users who already have verified emails or phone numbers and would like to migrate those users with a verified status, call the [Migrate Password](/api-reference/consumer/api/passwords/migrate) endpoint with the params `set_email_verified: true` and `set_phone_number_verified: true` respectively. If the user does not have a password in your existing auth system, you can pass in a dummy password hash, then [Delete](/api-reference/consumer/api/users/delete/delete-user-password) it afterwards. Note that improperly setting email addresses or phone numbers as verified can open up a security gap in your application.

    You will not be able to add additional factors onto new or migrated users unless their primary authentication factor is verified, to prevent account takeover attacks.

    We strongly recommend to only migrate both factors for users who have verified ownership over both of these factors, in order to prevent account takeovers.

    ## Password strength requirement changes

    See our Docs for password strength configuration [here](/consumer-auth/authentication/passwords/strength-policy).

    The default password strength policy is [zxcvbn](https://github.com/dropbox/zxcvbn), but Stytch offers configurability of this policy via the [Dashboard](https://stytch.com/dashboard/password-strength-config).

    For those migrating users with passwords, our recommendations are to:

    1. Turn off breach and strength checks on authentication, so that migrated users aren't subject to any changes in password strength requirements unless they ever voluntarily reset their password. This can be done in the Stytch [Dashboard](https://stytch.com/dashboard/password-strength-config).
    2. You may configure your strength requirements to match your current requirements, but we advise for all customers to adopt our strongest policy, [zxcvbn](https://github.com/dropbox/zxcvbn), in order to improve your security posture. You may have this new policy only apply to new users and existing users who are resetting their password via step 1.
  </Tab>

  <Tab title="B2B auth">
    Deploying a new authentication service is not always limited to just changing login and signup logic. If your backend logs auth-related events or has a pre-existing RBAC implementation, you may need to refactor this logic to point to Stytch’s APIs.

    ## Migrating SSO connections

    There are two ways to migrate over SSO connections from your existing auth system to Stytch:

    ### Option 1: Proxy connections

    This option is only available for SAML IdPs that are currently configured with redirect URLs to your domain.

    You will need to create a [SAML SSO connection](/api-reference/b2b/api/sso/saml-connection-object) in Stytch for each existing SSO connection you plan to migrate - use the `alternative_audience_uri` parameter to pass Stytch the existing Audience. You can then forward requests from the URLs you already have set up to the relevant Stytch Connection ACS URL we provide:

    <img src="https://mintcdn.com/stytch-34ca0595/jCmOQoXV28mXNOhP/images/resources/migrations/migrate-sso.svg?fit=max&auto=format&n=jCmOQoXV28mXNOhP&q=85&s=e58c2f2dfadab925eeedbc3bb5ec998e" alt="Migrate SSO" width="6077" height="3394" data-path="images/resources/migrations/migrate-sso.svg" />

    Below is an example of how you can set up a simple redirect service to redirect requests from the originally configured redirect URL to Stytch, thus preserving your customers' <Tooltip tip={idp}>IdP</Tooltip> setups while migrating the SAML response processing to Stytch:

    ```js theme={null}
    const getStytchConnectionId = async (oldIdentifier) => {
    // Function to get Stytch connection_id by old identifier from your database, where you'd keep a mapping
    };

    app.get('/old-sso/:identifier', async (req, res) => {
      const { identifier } = req.params;

      try {
        const connectionId = await getStytchConnectionId(identifier);

        // Redirect to Stytch's SSO callback URL with the connection_id
        const stytchCallbackUrl = `https://api.stytch.com/v1/b2b/sso/callback/SSO_CONNECTION_ID`;

        //This can be a 307 or a 303 redirect
        return res.redirect(307, stytchCallbackUrl);
      } catch (error) {
        return res.status(500).send('Internal server error');
      }
    });
    ```

    ### Option 2: Create new SSO connections

    For this option, you will need to change the SSO settings in your customer's IdPs to point to Stytch's ACS URLs directly. Follow these [SSO guides](/multi-tenant-auth/authentication/sso/overview) for more information on how to set up SSO.

    ## Ingesting events and managing visibility

    If your legacy auth provider requires you to set up log streams or webhooks for event visibility, here are a few examples of how to move that logic to Stytch.

    With Stytch, there are multiple ways to gain access to authentication-related logs.

    ### Option 1: Use webhooks

    You can enroll in webhooks through the Stytch Dashboard by specifying URL(s) at which you wish to receive the webhook POST requests and the type of events you wish to receive.

    Check out our [webhooks guide](/resources/workspace-management/webhooks) to learn how to keep your internal database records in sync with any changes that occur in Stytch's B2B SaaS API.

    ```js theme={null}
    // Example organization create via dashboard (dashboard.organization.create)
    {
        "project_id": "project-live-123-...",
        "event_id": "event-live-123-...",
        "action": "CREATE",
        "object_type": "organization",
        "source": "DASHBOARD",
        "id": "organization-live-123-...",
        "timestamp": "2024-03-07T18:49:32.760777783Z",
        "organization": { ... }
    }

    // Example update member event via SCIM (scim.member.update)
    {
        "project_id": "project-live-123-...",
        "event_id": "event-live-456-...",
        "action": "UPDATE",
        "object_type": "member",
        "source": "SCIM",
        "id": "member-live-123-...",
        "timestamp": "2024-03-07T18:49:32.760777783Z",
        "member": { ... }
    }

    // Example delete SAML connection event via JS SDK or API (direct.saml_connection.delete)
    {
        "project_id": "project-live-123-...",
        "event_id": "event-live-789-...",
        "action": "DELETE",
        "object_type": "saml_connection",
        "source": "DIRECT",
        "timestamp": "2024-03-07T18:49:32.760777783Z",
        "id": "saml-connection-live-123-..."
    }
    ```

    ### Option 2: Log calls and responses made to Stytch from within your own application

    Frontend SDK example, using Email Magic Links with JavaScript:

    ```js theme={null}
      const onSubmit: FormEventHandler = async (e) => {
        if (isValidEmail(email)) {
          const resp = await stytchB2BClient.magicLinks.email.send({
              email_address: 'sandbox@stytch.com',
              organization_id: 'organization-test-07971b06-ac8b-4cdb-9c15-63b17e653931',
          });
        };

          // Send the response of the call to your logging tool
          // This includes the user info and response code

          if (resp.status === 200) {
            Bugsnag.notify(resp);
            setEMLSent(STATUS.SENT);
          } else {
            Bugsnag.notify(e);
            setEMLSent(STATUS.ERROR);
          }
      };
    ```

    Backend SDK/API example, using Python:

    ```py theme={null}
      @app.route("/login_user", methods=["POST"])
      def login_user() -> str:
          resp = stytch_b2b_client.magic_links.email.send(
              email=request.form["email"],
              login_magic_link_url=MAGIC_LINK_URL,
              signup_magic_link_url=MAGIC_LINK_URL,
              organization_id=org_id
          )
          # Send the response of the call to your logging tool
          # This includes the user info and response code

          if resp.status_code == 200:
            bugsnag.notify(resp)

          if resp.status_code != 200:
              bugsnag.notify(resp)
              print(resp)
              return "something went wrong sending magic link"

          return render_template("emailSent.html")
    ```

    ### Option 3: Check out the event logs in the dashboard

    View the [Event Logs](https://stytch.com/dashboard/activity) in the Dashboard to debug your authentication flows.

    ## Migrating roles and permissions

    If your application has an authorization system that resembles role-based access control (RBAC), you can transfer roles and permissions over to Stytch's RBAC framework.

    Refer to our [RBAC guides](/multi-tenant-auth/enterprise-ready/rbac/create-rbac-policy) for more information and instructions on how to create roles, resources, and permissions, and how to programmatically assign roles to <Tooltip tip={member}>Members</Tooltip>.

    ## Pre-production testing

    If you run any automated or pre-production testing that includes authentication, here are a few best practices to move that to Stytch:

    * If you have multiple pre-production environments that need their own user bases, use the Stytch Dashboard to create multiple test environments and have each set of `test` keys map to each of your internal environments.
    * We recommend creating test users and organizations that can be used for any authentication testing and QA flows.

    ## Migrating over additional user data

    Our `trusted_metadata` supports nested JSON and can be used to migrate and store any additional user data.

    We recommend keeping this data limited to information that is required in the context of authentication; for example, internal identifiers, profile information, and other claims.

    **Keeping identifiers consistent**: If you have analytics or other internal processes that key off of your internal user ID reference, and would like these IDs to stay consistent, we recommend adding your internal user ID as `trusted_metadata`. Your backend should then default to reading ID from this value, but fall back to the Stytch `member_id` if it does not exist. Stytch does not currently support seeding user GUIDs.

    ## Email/phone verification status

    Stytch manages the email and phone verification status of users. When a Member is created in Stytch, the value of `email_address_verified` will be `false` until the user completes their first login that verifies ownership of that account (e.g., an Email Magic Link or OAuth login). The value of `mfa_phone_number_verified` will be `false` until the member completes a successful [SMS authenticate](/api-reference/b2b/api/mfa/otp/authenticate-sms-otp) flow.

    The one exception is our [Passwords Migrate endpoint](/api-reference/b2b/api/passwords/migrate), which will mark the Member's email as verified. Note that improperly setting email addresses as verified can open up a security gap in your application.

    ## Password strength requirement changes

    See our Docs for password strength configuration [here](/multi-tenant-auth/authentication/passwords/strength-policy).

    The default password strength policy is [zxcvbn](https://github.com/dropbox/zxcvbn), but you can configure a different password policy via the [Dashboard](https://stytch.com/dashboard/password-strength-config).

    For those migrating users with passwords, our recommendations are to:

    1. Turn off breach and strength checks on authentication, so that migrated users aren't subject to any changes in password strength requirements unless they ever voluntarily reset their password. This can be done in the Stytch [Dashboard](https://stytch.com/dashboard/password-strength-config).
    2. You may configure your strength requirements to match your current requirements, but we advise all customers to adopt our strongest policy, [zxcvbn](https://github.com/dropbox/zxcvbn), in order to improve your security posture. You may have this new policy only apply to new users and existing users who are resetting their password via step 1.
  </Tab>
</Tabs>
