Migrate Users to FusionAuth in Bulk

On this page

A bulk migration imports every user with the Import Users API and switches your applications to FusionAuth in one cutover. To decide whether a bulk migration fits, see Migration Types.

Before you start, complete the following:

  • Plan the migration and set up FusionAuth. For more information, see Plan a Migration.
  • Create the Tenants, Applications, and Groups that the users belong to. The import doesn't create them.

Tune Performance#

A bulk migration includes an outage, so the import should run fast. Apply the following settings and tasks:

For best performance, do the following:

  • Minimize the number of network hops; load the data from a server on the same network.
  • Run with the validateDbConstraints set to false.
  • Make sure the JSON is minified.
  • Load in batches of 10k.
  • If you have tens of millions of users and are self-hosting, consider switching to the database search engine. With that option, FusionAuth won't sync user data to Elasticsearch during the import. If you require Elasticsearch for advanced searching capabilities, switch back to Elasticsearch after the migration is complete. This option is not available when using FusionAuth Cloud.
  • Disable the user.bulk.create webhook. This may not be possible if you need FusionAuth to send an event with created users to another system.
  • Set the HTTP timeout to a large value on your API requests. Exactly how to do this varies based on the tool you're using to make the HTTP request. The import API is currently a synchronous operation, though there are plans to make it asynchronous (see this GitHub issue for more).
  • If you only provide a password field, then FusionAuth will assume the password is in plaintext and hash it for you. Hashing a password negatively affects load time, performance and throughput. If you provide the salt, password, encryptionScheme and factor values when importing, then FusionAuth assumes the value in the password field is a hashed password, and it will not be hashed.
  • Deduplicate any emails. In FusionAuth, each email address may be associated with only one user account per tenant.
  • Stage your data by exporting current user data into separate JSON files. This will make debugging easier, since you can load one file at a time, and you can repeat a data load if there are issues. It will also be more performant than loading data across a network or from a database.
  • For easy testing, you can use or modify this Ruby script to generate and import large numbers of users with a hashed password of 'password'.
Note

The easiest and fastest way to load bulk user data into FusionAuth is to loop over a directory of JSON files that each contain 100,000 users. These JSON files should be clean, have unique emails per tenant and be minified.

In FusionAuth testing, this approach resulted in loading 100,000 users in 62 seconds to an HA FusionAuth Cloud deployment from one EC2 region to another. Performance is dependent on user data complexity, hardware, network and database constraints, but this should give you a good idea of the order of magnitude.

Write the Import Scripts#

  1. Run a FusionAuth instance for testing. To start the instance in a known state every time, configure Kickstart. A Kickstart file can also create the Tenants, Applications, and Groups, and later serves developers and CI.

  2. Create an API key with the POST method on the /api/user/import endpoint. For more information, see Managing API Keys.

    The details of an API key that can import users.
  3. Write a script that reads every user from the old system and builds an import request body. Add a Registration for each Application that the user needs. Write the scripts in any language that sends HTTP requests, or with a client library.

  4. Set encryptionScheme, factor, and salt on each user to match the old hashing scheme. The field name says "encryption" for backward compatibility, but the value names a hashing scheme. When FusionAuth doesn't support the scheme, write and install a plugin first. For more information, see Password Hashing Algorithms and Custom Password Hashing.

  5. Send the request bodies to the Import Users API, either with the importUsers method of a client library or with a direct HTTP request.

The following example request body imports one user. Add more objects to the users array to import more users in one request:

Example User Import JSON Request Body
{
  "users": [
    {
      "active": true,
      "birthDate": "1976-05-30",
      "data": {
        "displayName": "Johnny Boy",
        "favoriteColors": [
          "Red",
          "Blue"
        ]
      },
      "email": "example@fusionauth.io",
      "encryptionScheme": "salted-sha256",
      "expiry": 1571786483322,
      "factor": 24000,
      "firstName": "John",
      "fullName": "John Doe",
      "imageUrl": "http://65.media.tumblr.com/tumblr_l7dbl0MHbU1qz50x3o1_500.png",
      "insertInstant": 1331449200000,
      "lastName": "Doe",
      "memberships": [
        {
          "data": {
            "externalId": "cc6714c6-286c-411c-a6bc-ee413cda1dbc"
          },
          "groupId": "2cb5c83f-53ff-4d16-88bd-c5e3802111a5"
        }
      ],
      "middleName": "William",
      "mobilePhone": "303-555-1234",
      "password": "5ac152b6f8bdb8bb12959548d542cb237c4a730064bf88bbb8dd6e204912baad",
      "passwordChangeRequired": false,
      "phoneNumber": "303-555-1212",
      "preferredLanguages": [
        "en",
        "fr"
      ],
      "registrations": [
        {
          "applicationId": "00000000-0000-0000-0000-000000000002",
          "data": {
            "birthplace": "Bremen"
          },
          "insertInstant": 1331449200000,
          "preferredLanguages": [
            "de"
          ],
          "roles": [
            "moderator"
          ],
          "username": "Mausebär",
          "verified": true
        }
      ],
      "salt": "NDdiYWZkZDMtYjk5ZC00ZmZkLWE1YmUtZTQxNGM4MDkwNWYw",
      "timezone": "America/Denver",
      "twoFactor": {
        "methods": [
          {
            "authenticator": {
              "algorithm": "HmacSHA1",
              "codeLength": 6,
              "timeStep": 30
            },
            "secret": "aGVsbG8Kd29ybGQKaGVsbG8gaGVsbG8=",
            "method": "authenticator"
          },
          {
            "method": "sms",
            "mobilePhone": "555-555-5555"
          },
          {
            "method": "email",
            "email": "example@fusionauth.io"
          }
        ]
      },
      "usernameStatus": "ACTIVE",
      "username": "johnny123",
      "verified": true
    }
  ]
}

The best batch size depends on the size of your deployment. On a production-ready deployment, 100,000 users per request is a reasonable batch size.

Build the request bodies as files when you can. Files make a failed batch easy to inspect and retry. When you merge two data sources on the fly, you can build the request bodies in memory instead, at the cost of harder troubleshooting.

The following shell script sends every JSON file in a directory to the Import Users API. The script allows each request 10 minutes, and stops at the first response with a status other than 200:

Example User Import Shell Script
#!/bin/sh

API_KEY=...
JSON_FILE_DIR=...
FA_HOST=...

for file in $JSON_FILE_DIR/*.json; do
  echo "Processing $file";
  RES=`curl --max-time 600 \
       -s -o /dev/null -w "%{http_code}" \
       -H "Authorization: $API_KEY" \
       -H "Content-type: application/json" \
       -XPOST \
       $FA_HOST/api/user/import \
       -d@$file`
  if [ "$RES" -ne "200" ]; then
    echo "Error: $RES";
    exit 1;
  fi
done

For the full list of fields, see the Import Users API.

Handle Duplicate Email Addresses#

FusionAuth doesn't allow two users with the same email address in one Tenant. Remove or merge duplicates before you import. By default, the Import Users API checks no constraints in advance, and a duplicate fails the whole request with a general error:

Import Error Message When validateDbConstraints is false
{
  "generalErrors": [{
    "code": "[ImportRequestFailed]",
    "message": "An error occurred during the import request. This is most likely due to a unique key constraint which would indicate one or more of the users in the import request already exist in FusionAuth. Re-attempt the request with additional validation by using the [validateDbConstraints] property. If you have already enabled the additional validation and you still receive this error, please open a bug report."
  }]
}

To find the duplicates, set validateDbConstraints to true in the request body. The Import Users API then names the duplicate:

Import Error Message When validateDbConstraints is true
{
  "fieldErrors": {
    "user.email": [{
      "code": "[duplicate]user.email",
      "message": "A user with email [example@piedpiper.com] already exists."
    }]
  },
  "generalErrors": []
}

The extra validation slows the import. Run the import once with validateDbConstraints set to true to find and fix the duplicates. Then run the real import with validateDbConstraints set to false.

Rehash User Passwords#

When you import users with their existing password hashes, users log in without resetting their passwords. FusionAuth keeps each imported hash and the hash's scheme, which may be weak. To replace weak hashes, configure the Tenant to rehash passwords with a stronger scheme:

  1. Import the users with their existing hashes. When FusionAuth doesn't support the old scheme, write a password hashing plugin for the scheme. For more information, see Custom Password Hashing.
  2. In the Admin UI, navigate to Tenants -> Your Tenant -> Password .
  3. In the Cryptographic hash settings section, set Scheme to the new scheme. FusionAuth also uses the new scheme for users that you create in the Tenant later.
  4. Turn on Re-hash on login or change.
  5. Click .
Tenant settings for rehashing passwords on login.

FusionAuth then rehashes a user's password with the new scheme when the user logs in. In FusionAuth 1.42.0 and later, FusionAuth also rehashes the password when the password changes.

Users Without Passwords#

In FusionAuth 1.59.0 and later, the Import Users API accepts users without passwords. Leave out password for these users. A user without a password can log in with a passwordless method or an Identity Provider. To let these users set a password, send each user an email with the Forgot Password API.

In FusionAuth versions earlier than 1.59.0, the Import Users API requires a password for every user. Give each of these users a high-entropy password, such as a UUID, and then send each user an email with the Forgot Password API. Alternatively, create these users one at a time with the Create a User API, which can send a set password email.

Both approaches send one email per user. Count the users without passwords, and confirm that your email infrastructure can handle the volume.

Users With Social Logins#

Migrating users with social logins such as Apple or Facebook requires that you have an existing user Id for that provider. What this unique user Id looks like depends on the particular social identity provider. The unique Id may be an email address, an integer, UUID, or a random string.

Configure the appropriate FusionAuth Identity Provider with the same values (client_id, etc) as the original user management system you are migrating away from.

Import users with the Import API, assigning each user with a social login a random password such as a UUID.

Your next step depends on whether the social login provider's unique identifier is available as part of your migration data. If you have the social login provider's unique identifier, for each user, use the Link API to create a link with the appropriate User Id, Identity Provider Id, and Identity Provider User Id.

  • The User Id is the Id of the recently created FusionAuth User.
  • The Identity Provider Id is found on the corresponding Identity Provider API documentation. Look for identityProvider.id.
  • The Identity Provider User Id is the existing social provider user identifier exported or otherwise extracted from the original system.

You do not need to migrate the social network token, which may or may not be accessible. During the first login of a newly migrated user, FusionAuth finds the unique user in the social login provider based on the migrated Identity Provider User Id, and completes the login. During this process, FusionAuth stores a token on the Link, if the social provider returns one. Depending on the configuration of the social provider, users may see a prompt asking if they want to allow FusionAuth to have access to user data such as email address.

Available since 1.28.0

IdP linking strategies have been available since version 1.28.0. Before that version, users were linked on email.

If you do not have the social login provider's identifier, you need to decide if you want to transparently link the two accounts, which is easier for the end user, or if you want to ask the user to manually link the accounts, which is more accurate, but may be confusing.

To transparently link the accounts, choose a linking strategy of Link On Email or Link On Username, which will create the user if they don't exist. However, if the user has an email address at their social provider which differs from the email address that was used to sign up for your application and which you imported to FusionAuth, then two accounts will be created.

For example, if the user has a Google account richard@gmail.com, but signed up for your application with richard@fusionauth.io, then if you use the Link On Email strategy, two different accounts will be created, since FusionAuth is trying to match on email address and they don't. The same holds true for usernames with the Link on Username strategy.

To prompt the user to link the accounts, choose a linking strategy of Pending, which will prompt the end user to sign into FusionAuth after they sign into the social provider, authoritatively linking the two accounts.

Here's more information about IdP Linking Strategies.

Note

Apple only returns a user's full name the first time the user logs in. Since you have users who have already used Apple to log in to your previous authentication gateway, Apple will not provide the user's name when they log in to FusionAuth now. The only solution is to import the user's name manually from your previous database into FusionAuth.

Users With MFA#

FusionAuth can import users with authenticator, email, and SMS methods. Set the twoFactor fields on each user in a request to the Import Users API for a bulk migration, or the User API for a slow migration. The following example adds two email methods:

The twoFactor object for a user with two email methods
"twoFactor": {
  "methods": [{
    "method": "email",
    "email": "dinesh@aol.com"
  },
  {
    "method": "email",
    "email": "dinesh@gmail.com"
  }]
}

For an authenticator method, include the base64-encoded secret from the old system, so the user's authenticator app keeps working. The Import Users API also accepts the user's existing recoveryCodes.

When the old system uses a message-based method that FusionAuth doesn't support, such as push notifications, a Generic Messenger may fit. The Generic Messenger sends SMS method codes to a service you run. For any other method, open a GitHub issue that describes your use case.

Test the Import#

Test the import with as much data as possible, ideally every user. A full-size test shows how long the import takes. Real data also reveals edge cases, such as duplicate email addresses and malformed attributes.

Import into a separate Tenant, such as a Testing Tenant, even when production uses one Tenant. Deleting a Tenant deletes the Tenant's users, Applications, Groups, and settings, so you can rerun the scripts from a clean state. You can't delete the Default Tenant, which contains the FusionAuth Application.

After the import works, point your applications at the test instance and log in with real migrated users. The prototype from the evaluation used test data, so this test checks your assumptions against the real data.

To remove the imported users between test runs, use one of the following:

  • Delete the test Tenant. Settings outside the Tenant, such as Identity Providers, email templates, and themes, stay in place.
  • Drop the database, and create a new one with Kickstart or Terraform.
  • Delete users with the Bulk Delete API. Start with batches of 5,000 to 10,000 users, and grow the batches with each call. Bulk deletion is the slowest option, but leaves the rest of the instance untouched.

Run the Migration#

  1. Tell internal stakeholders about the migration and the outage. Your test runs show how long the outage lasts. You can avoid the outage only when your applications can run with the old user store read-only.
  2. Run the import against the production data.
  3. Release the application changes that send users to FusionAuth for login, registration when applicable, forgot password, and password changes.

To roll back, revert the application changes. When users changed profile data in FusionAuth, copy the changes back to the old system. A script that searches the Users API for recent updates is a starting point, but the details depend on your applications.

Migrate Segment by Segment#

A segment-by-segment migration repeats the bulk procedure for each segment of users, such as the users of one Application or the users with one role. The planning, mapping, and import work the same way, for a smaller group each time.

The cutover differs, because FusionAuth doesn't have every user yet. How you route users depends on the segments:

  • When you segment by Application, update one Application at a time to send users to FusionAuth.
  • When you segment by another attribute, add logic to your applications that decides where to send each user at login.

Import From Another FusionAuth Instance#

FusionAuth has no built-in way to copy users from one FusionAuth instance to another. Treat the other instance as any other data source. Follow the Generic Migration Tutorial, and adapt the export and import scripts from the example repository.