Migrate Users From a Custom Authentication System

On this page

This tutorial migrates the users of a small Express app with custom authentication to FusionAuth. The tutorial covers exporting password hashes, mapping users to FusionAuth fields, importing users with the API, and switching the app to log in through FusionAuth. To plan a migration at a higher level, see the FusionAuth migration guide.

Prerequisites#

To import passwords along with personal details, you need a basic understanding of password hashes and salts. For an introduction, see The Math of Password Hashing Algorithms And Entropy.

The example app, the migration scripts, and FusionAuth run in Docker.

Note

When your hosts file has no entry for host.docker.internal, add one. On macOS and Linux, run the following command:

$ echo "127.0.0.1 host.docker.internal" | sudo tee -a /etc/hosts

To run the scripts on your machine instead of in Docker, install Node.js. Then replace db and host.docker.internal with localhost in every script.

Planning Considerations#

Mapping User Attributes#

The attributes of the User object in FusionAuth are well documented.

If there is an attribute in your exported user which cannot be directly mapped to a FusionAuth attribute, you can place it in the user.data field. This field can store arbitrary JSON values and will be indexed and searchable.

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.

Other Entities#

Plan to migrate other important entities, such as connections or roles. These entities are usually few, so automating the migration may not pay off. Migrate the configuration by hand or with a script.

Features may differ between your Custom Authentication System and FusionAuth. User data is simpler: a user who arrives with a login identifier, such as an email address or username, and a password hash can log in to FusionAuth. To learn the differences before you migrate, download FusionAuth and build a proof of concept.

The entities to migrate for your application can include the following:

  • When your application uses roles, FusionAuth configures roles per application. FusionAuth adds a user's roles to the token after a successful login.
  • To manage separate sets of users, use Tenants.
  • When your application sends emails, such as forgot password notifications, FusionAuth sends the same emails with customizable templates. For more information, see Email Templates.
  • FusionAuth stores custom user attributes in the user.data field. The field accepts any valid JSON value, has no size limit, and is searchable.
  • When your application uses multi-factor authentication (MFA), turn on MFA in FusionAuth. For more information, see Multi-Factor Authentication.

Identifiers#

When you create an object with the FusionAuth API, you can set the object's Id. The Id must be a UUID. Users, Applications, Tenants, and most other objects accept an Id.

Exporting Users#

The example app has a sign-in page, a restricted account page, and a PostgreSQL database with one table of users and password hashes.

Start the Example App#

Clone the import scripts repository:

$ git clone https://github.com/FusionAuth/fusionauth-import-scripts

The generic directory holds the code for this tutorial. The generic/exampleData directory holds sample output from the scripts.

Start the app and the app's database in Docker:

$ cd fusionauth-import-scripts/generic/src
$ docker compose --file 1_appDockerCompose.yaml up

Create the User Table#

Open a new terminal in the fusionauth-import-scripts/generic/src directory. Open a shell in the app container:

$ docker exec --interactive --tty app sh

Run every script in the rest of the tutorial in this container shell. Install the dependencies, and create the user table:

$ cd /workspace && \
npm install && \
node 2_createUser.mjs

The 2_createUser.mjs script creates a user table with the text columns email, hash, and salt.

To browse the table, connect a PostgreSQL client such as DBeaver to localhost on port 7770. Use the database p, the username p, and the password p.

Run the Web App#

In the container shell, start the Express app:

$ node 3_webApp.mjs

Browse to http://localhost:7771/account. The account page is restricted, so the app denies access.

Browse to http://localhost:7771, and sign in with the email user@example.com and the password password. The app creates the user in the database and redirects you to the account page. The app now stores your email address in the session, so the account page shows your details.

The app in 3_webApp.mjs has GET routes for the home page and the account page. The POST route for the home page does the following:

  • Rejects the request when the email or password is missing.
  • Looks up the email in the database.
  • When the email exists, hashes the entered password with the stored salt and compares the result with the stored hash.
  • When the email doesn't exist, creates the user with a random UUID as the salt.

The getHash function at the end of the file hashes the password and salt with 20,000 rounds of SHA-256. FusionAuth supports this scheme natively as salted-sha256. For more information, see Salted SHA-256. When your app uses a scheme that FusionAuth doesn't support, see Writing a Plugin.

Press Ctrl+C in the container shell to stop the app.

Create a Users File#

In the container shell, export the users to users.json:

$ node 4_exportUsers.mjs

For a real app, write the export in any language. A SQL query against your database is the most common choice.

The 5_convertUserToFaUser.mjs script maps the fields in users.json to FusionAuth User fields. The example app stores only an email and a password, so a real app needs a larger mapping. For the full list of User fields, see the Users API.

The script reads users.json with stream-json, which reads a file incrementally and handles files with millions of users. The processUsers() function passes each user to getFaUserFromUser() and writes the result to faUsers.json.

The getFaUserFromUser() function does the following:

  • Copies the fields that match FusionAuth fields.
  • Sets encryptionScheme to salted-sha256 and factor to 20000.
  • Converts the salt to Base64, the format that FusionAuth expects.
  • Adds a registration for the Test application. Change the Application Id to your own for a real migration.
  • Sets data.ImportedFromExpressJs to true. Store any field without a FusionAuth equivalent in data.

Run the script in the container shell:

$ node 5_convertUserToFaUser.mjs

The output is a JSON array like the one in fusionauth-import-scripts/generic/exampleData/faUsers.json.

Importing Users#

To start a FusionAuth instance for testing, open a new terminal in the fusionauth-import-scripts directory and run the following commands:

$ cd generic/fusionAuthDockerFiles && \
docker compose up

FusionAuth runs at http://localhost:9011 in a container named fa. Log in to the Admin UI with the email admin@example.com and the password password.

The instance configures itself with KickstartA file of API requests that FusionAuth runs on first startup to configure a new instance. from generic/fusionAuthDockerFiles/kickstart/kickstart.json. The Kickstart file creates an API key, an admin user, a theme, and the Test application. For more information, see Kickstart.

In the container shell, import the users from faUsers.json:

$ node 6_importUsers.mjs

The script calls importUsers() from the TypeScript client library once for each user. For a large migration, send many users in each call. For batch sizes, see the Import Users API.

Verify the Import#

To confirm that an imported user can log in:

  1. In the Admin UI, navigate to Applications .

  2. Click Select for the Test application, choose View , and copy a URL from Login URLs.

    The application details dialog with the login URLs highlighted.
    The application details dialog with the login URLs highlighted.
  3. Open the URL in a private browser window, so the admin session doesn't interfere.

  4. Log in with the email user@example.com and the password password.

FusionAuth redirects to a URL like http://example.com/?code=2aUqU0ZhQCjtz0fnrFL_i7wxhIAh7cTfxAXEIpJE-5w&locale=en&userState=.... The Test application doesn't handle the authorization code yet. Use FusionAuth as Your Authentication Provider sets up the app to handle the code.

To review the imported data, navigate to Users in the Admin UI.

The user list with the imported users highlighted.
The user list with the imported users highlighted.

Click Select for a user, and choose Manage . The Source tab shows the user as JSON.

Debug With the FusionAuth Database#

When an imported user can't log in, check the user and the hash in the FusionAuth database. Connect a PostgreSQL client with the following details from docker-compose.yml and .env in generic/fusionAuthDockerFiles:

  • URL: jdbc:postgresql://localhost:5432/fusionauth
  • Host: localhost
  • Port: 5432
  • Database: fusionauth
  • Username: fusionauth
  • Password: hkaLBM3RVnyYeYeqE3WI1w2e4Avpy0Wd5O3s3

Open Databases/fusionauth/Schemas/public/Tables. The identities table holds each user's login identifiers, such as the email address. The users table holds the password hash settings and personal details.

Use FusionAuth as Your Authentication Provider#

To switch the example app to log in through FusionAuth:

  1. In the Admin UI, navigate to Applications . Click Select for the Test application, and choose Edit .

  2. On the OAuth tab, set Authorized redirect URLs to http://localhost:7771/callback, which is the app's callback URLThe URL where the authorization server sends the browser after login, with an authorization code or an error..

    The authorized redirect URL on the application OAuth tab.
    The authorized redirect URL on the application OAuth tab.
  3. Click Save .

  4. In the container shell, start the version of the app that uses FusionAuth:

    $ node 7_webAppWithFa.mjs
    
  5. Browse to http://localhost:7771. FusionAuth shows the login page in place of the app's sign-in page.

The new app matches the original, except that OAuth calls to FusionAuth through Passport replace the login and hashing code. To style the login page, or for a full walkthrough of an Express integration, see the Express QuickStart.

Caution

The authOptions object at the end of 7_webAppWithFa.mjs stores secrets in the code. In a real app, move the secrets to a .env file that stays out of source control. For URLs that the server calls, use host.docker.internal instead of localhost. Browser URLs keep localhost.

Delete the Docker Containers#

Press Ctrl+C in every terminal to stop the containers. When you finish testing, remove the containers and images from your machine:

$ docker rm app app_db fa fa_db && \
docker rmi postgres:16.2-alpine3.19 node:alpine3.19 fusionauth/fusionauth-app:latest postgres:16.0-bookworm

What to Do Next#

The example app hashes passwords with salted SHA-256, which is weaker than modern schemes. To rehash each password with a stronger scheme at the user's next login, turn on Re-hash on login or change in the Tenant. For more information, see Rehashing User Passwords.

After the users move, migrate the other configuration described in Other Entities. The steps vary by configuration, but follow this pattern:

  • Find the matching FusionAuth feature.
  • Configure the feature in FusionAuth, either in the Admin UI or with a script that uses the client libraries or the APIs.
  • Update your application configuration to use the FusionAuth feature.

Register your users with the right FusionAuth Applications in one of the following ways:

  • Add Registrations to the users during the import.
  • Create Registrations after the import with the Registrations API.

Change and test each application, whether custom, open source, or commercial, and confirm the following:

  • Users can log in.
  • The application handles the authorization code redirect.
  • Users get the right permissions and roles from the JWT.
  • The hosted login pages match the look and feel of the application.

When an application talks to your current system through a standard OAuth, SAML, or OIDC library, the switch to FusionAuth usually takes few changes.

Additional Support#

If you need support in your migration beyond that provided in this guide, you may: