Easily Migrate Your Existing Users to Auth0

User migration is a dreaded, sometimes unavoidable task that is difficult for developers, inconvenient for users, and expensive for business owners. The need for migrating users from one service or platform to another can stem from any number of reasons: the identity provider you are currently using is shutting down, your organization no longer wishes to manage users themselves, a change in language or framework, and many other reasons.

Auth0 aims to provide the best authentication and identity management platform that is simple and easy for developers to work with. A key feature of the Auth0 platform is the ability to migrate users from any existing data source into Auth0 without inconveniencing users by requiring password changes.

In this tutorial, we’ll take a look at how to do just that. Stormpath is a company that provides authentication as a service and was recently acquired by Okta. Okta has announced that the Stormpath product will be shut down in August 2017 and customers have until then to find a new provider. Let’s see how we can easily migrate existing Stormpath users into Auth0.

User Migration Made Easy with Auth0

Auth0 allows customers to connect to any custom datastore using the custom database connection feature. This feature, as the name may suggest, allows Auth0 to validate user credentials that are stored outside of Auth0. The external data store can be a database such as MySQL, a service like Stormpath, or your own custom implementation. These external data sources are accessed via scripts written in the Auth0 dashboard. The custom database connection feature also allows developers to automatically import users logging in with custom database credentials into Auth0. This feature can be enabled with the flip of a switch.

To implement this feature in the context of migrating Stormpath users to Auth0, we’ll set up a custom database connection and connect it to an existing Stormpath account using the Stormpath API. When your users log in the first time, they will enter their existing Stormpath credentials and, if authenticated successfully, we will automatically migrate that user account from Stormpath into Auth0. Your users will not have to change their password or jump through any additional hoops and you can decide what data to port over from Stormpath. The next time the user logs in, Auth0 will detect that they have been migrated and authenticate them with their Auth0 account.

Migration diagram

To get started, first sign up for a free Auth0 account. We’ll assume that you already have an active Stormpath account with users you wish to migrate. Even if you are not using Stormpath, you can follow along with this tutorial and connect to a different datastore.

Setting up a Custom Database Connection with User Import Functionality

With your account created, let’s set up a custom database connection. In your Auth0 management dashboard, navigate to the database connections section.

Create DB connection

Click on the Create DB Connection button to create a new database connection. You can name your connection anything you like. Leave all the default settings as is for now and click the Create button to create the connection.

Configure DB

Next, let’s go into this database connection and connect it to our Stormpath account. Click on your newly created connection and navigate to the Custom Database tab. Flip the switch titled “Use my own database” and the Database Action Scripts section will now be enabled. This is where we will write our code to connect to your existing Stormpath user datastore.

We will need to write two scripts: Login and Get User. Login will proxy the login process and Get User will manage looking up accounts when a user attempts to reset their password.

Enable custom DB

With our custom database feature turned on, let’s enable the import functionality. By default, the custom database connection will allow us to authenticate with an external database and will not import users to Auth0. If we want to migrate users from the external platform into Auth0 we’ll need to simply toggle a switch. Go to the Settings tab of the connection and flip the switch titled “Import Users to Auth0” and you’re done.

Import to Auth0

One final step we’ll do before implementing our scripts is enabling this connection for our default client. Navigate to the Clients tab while you are in your database connection and flip the switch to enable this client for the Default Connection. If you already have an existing Auth0 account, the connection name may be different.

Enable connection

Login

The Login script is executed when a user attempts to sign in but their account is not found in the Auth0 database. Here we will implement the functionality to pass the user credentials provided to our Stormpath user data store and see if that user is valid. Auth0 provides templates for many common databases such as MongoDB, MySQL and SQL Server, as well as Stormpath. These templates provide a great starting point and you can customize them any way you want or write your own from scratch.

The Database Action Scripts run in a Webtask sandbox and are Node.js scripts. As our tutorial is focused on migrating Stormpath users to Auth0, the scripts shown below will be geared towards working with the Stormpath REST API, but if you are migrating users from a different provider, you would write your implementation here or use one of the other templates provided.

Let’s look at the Login script implementation to see how it works. We will utilize Stormpath’s REST API to authenticate the user.

function login(username, password, callback) {
  // Replace the YOUR-STORMPATH-CLIENT-ID with your Stormpath ID
  var url = 'https://api.stormpath.com/v1/applications/{YOUR-STORMPATH-CLIENT-ID}/loginAttempts';
  // Add your Stormpath API Client ID and Secret
  var apiCredentials = {
    user : 'YOUR-STORMPATH-API-ID',
    password: 'YOUR-STORMPATH-API-SECRET'
  }

  // Stormpath requires the user credentials be passed in as a base64 encoded message
  var credentials = new Buffer(username + ':' + password).toString('base64');

  // Make a POST request to authenticate a user
  request({
    url: url,
    method: 'POST',
    auth: apiCredentials,
    json: {
      type: 'basic',
      // Passing in the base64 encoded credentials
      value: credentials
    }
  }, function (error, response, body) {
    // If response is successful we'll continue
    if (response.statusCode !== 200) return callback();
    // A successful response will return a URL to get the user information
    var accountUrl = body.account.href;

    // Make a second request to get the user info.
    request({
      url: accountUrl,
      auth: apiCredentials,
      json: true
    }, function (errorUserInfo, responseUserInfo, bodyUserInfo) {
      // If we get a successful response, we'll process it
      if (responseUserInfo.statusCode !== 200) return callback();

      // To get the user identifier, we'll strip out the Stormpath API
      var id = bodyUserInfo.href.replace('https://api.stormpath.com/v1/accounts/', '');

      // Finally, we'll set the data we want to store in Auth0 and migrate the user
      return callback(null, {
        user_id : id,
        username: bodyUserInfo.username,
        email: bodyUserInfo.email,
        // We set the users email_verified to true as we assume if they were a valid
        // user in Stormpath, they have already verified their email
        // If this field is not set, the user will get an email asking them to verify
        // their account. You can decide how to handle this for your use case
        email_verified: true
        // Add any additional fields you would like to carry over from Stormpath
      });
    });
  });
}

Continue reading %Easily Migrate Your Existing Users to Auth0%


Source: Sitepoint