Using UnifyID GaitAuth™ with IFTTT Rules

Security for your digital life is more important today than ever, but it can be a real pain. Mobile authentication typically means getting out your phone, unlocking it, opening an app, remembering a password, authenticating in the app. Authentication via biometrics like fingerprints or facial recognition are a step in the right direction, but assume you have an ungloved finger or unmasked face available, among other potential shortcomings. 

UnifyID offers a novel new method of uniquely authenticating using the way you walk. With GaitAuth, an app can provide authenticated user functionality as long as the user is carrying their phone as they walk around. 

In this article, we’ll show how easy it is to integrate GaitAuth into a mobile app and use GaitAuth to authenticate the device’s user before triggering an IFTTT Webhook that could be used for sensitive tasks like home automation and security.

What is GaitAuth?

GaitAuth aims to remove the friction from mobile authentication. 

Anyone who has used a modern mobile device knows that passwords and personally identifiable information are not convenient nor, in practice, all that secure. Multi-factor authentication can help, but many popular authentication factors have drawbacks. For example, codes sent via SMS are susceptible to attacks like SMS spoofing and SIM hijacking.

GaitAuth uses motion-based behavioral biometrics and environmental factors to create a unique digital fingerprint of a mobile device’s user. GaitAuth uses this fingerprint to ensure the user is who they claim to be. This kind of passive authentication means no user disruption and real-time protection.

Even better, the GaitAuth SDK lets you easily incorporate GaitAuth into your mobile apps to provide machine learning-powered authentication. 

How does IFTTT fit in?

IFTTT is a popular automation platform that enables even non-technical users to create automations. Using IFTTT, it’s easy to set up workflows that perform actions in one or more services based on events triggered by a device or service. 

For example, a user with a Ring doorbell could use IFTTT to turn on their house’s interior smart lights if the doorbell detects motion in front of the house. But when manipulating user data and working with home automation devices like smart locks, it’s important to verify the user’s identity. 

For example, what if you could unlock a smart lock for your child just by having them walk up to the door? You want to be certain it’s your child walking up to the door before unlocking it. GaitAuth can provide that certainty. 

Getting started with GaitAuth and iOS

Let’s take a look at how you might use GaitAuth to authenticate IFTTT automations in an iOS app. Before you start, make sure you have CocoaPods installed. It’s the preferred installation method for both the GaitAuth and IFTTT iOS SDKs. 

You’ll also need to sign up for a UnifyID developer account so you can obtain an SDK key.

Start by opening Xcode and creating a new iOS app. To keep things straightforward, create a single-view iOS app using Storyboards.

Next, set up a Podfile in your app’s Xcode project directory, and follow the instructions for installing the GaitAuth and IFTTT dependencies. You’ll end up with a Podfile like this:

target 'GaitAuthIFTTT' do
    pod 'UnifyID/GaitAuth'
    pod 'IFTTTConnectSDK'
end

# Enable library evolution support on all dependent projects.
post_install do |pi|
    pi.pods_project.targets.each do |t|
        t.build_configurations.each do |config|
          config.build_settings['BUILD_LIBRARY_FOR_DISTRIBUTION'] = 'YES'
        end
    end
end

Run pod install from the terminal to install both SDKs. Now add the code needed to set up and use GaitAuth. Start by adding this line to the top of AppDelegate.swift:

import UnifyID

Then, initialize UnifyID just inside the AppDelegate class:

let unifyid : UnifyID = { try! UnifyID(
    sdkKey: "https://xxx@config.unify.id",
    user: "unique-immutable-user-identifier"
)}()

You can generate a real SDK key in the UnifyID developer portal. The user attribute can be set to anything you’d like, as long as no two users of your app have the same identifier. Once you’ve chosen an identifier for a user, use the same value every time that person uses your app.

Using GaitAuth in your iOS apps

The first step in using GaitAuth is creating and training a model. When training is complete, GaitAuth uses this model to identify and authenticate the user of the device. 

To train a GaitAuth model, we’ll use the following steps:

  1. Create a model on an iOS device.
  2. Add features to the model. Features represent data about the way the iOS device’s user walks. We’ll need to gather this data to train a GaitAuth model.
  3. Enqueue the model for server-side training.
  4. Check the status of the model on the server until it is ready.
  5. Download the trained model from the server to the device where your app is running.
  6. Use the trained model in your app to score newly collected features — which GaitAuth does automatically as the user walks around while carrying the device. This lets you authenticate quickly and easily.

Let’s examine how this process looks in Swift. To start using GaitAuth in your app, obtain an instance of it by calling:

let gaitAuth = unifyid.gaitAuth

Before we can effectively use GaitAuth in an iOS app, we’ll have to train a GaitAuth model to learn about your app user’s gait. Next, we create a model:

gaitAuth.createModel { result in
    switch result {
    case .success(let gaitModel):
        // Save gaitModel.id
    case .failure(let error):
        // Handle the error
    }
}

It’s important to save the model ID so we’ll be able to re-load this model from the server if necessary. With the model created, we can start gathering data about the device user’s gait:

gaitAuth.startFeatureUpdates(to: DispatchQueue.main) { result in
    switch result {
    case .success(let features):
        // Called when feature collection is complete
    case .failure(let error):
        // Handle the error
    }
}

Seven days’ training time is optimal. When the app has gathered enough feature data, call:

gaitAuth.stopFeatureUpdates()

This will call the .success result handler, and the features will be ready to use. Note that you need to use an iOS background mode to ensure model training continues even when the app isn’t currently on-screen. If this isn’t possible, use the feature serialization functionality described in the GaitAuth documentation to save the feature data that’s been gathered. This lets the app add to the existing feature collection when execution resumes. 

Next, we add features to the model:

gaitModel.add(features) { error in
    if let error = error {
        // Handle the error
        return
    }
    // Successfully added gait features to model
}

…and start the training process:

gaitModel.train() { error in
    if let error = error {
        // Handle the error
        return
    }
    // Training is in progress. Notify the user if necessary.
}

Training occurs on the GaitAuth server, and can take a few hours. When training is complete, the model’s .status property will be ‘ready‘, so the app should periodically check the status to determine when the model is ready to use for authentication.

Setting up an IFTTT Webhook

Now we’ll set up an IFTTT Webhook. Before proceeding, create a free IFTTT account. 

Start by opening the IFTTT dashboard at https://ifttt.com/home. Then, click ‘Create‘ to add a new Applet:

A picture containing text

Description automatically generated

Then, add an ‘If This’:

A picture containing text, clipart

Description automatically generated

Search for Webhooks and select it:

Graphical user interface, application, Teams

Description automatically generated

And choose ‘Receive a web request’:

Graphical user interface, text, application

Description automatically generated

Enter an event name like ‘gaitauth_trigger‘, and click ‘Create Trigger‘. Finally, add a ‘Then That’ to determine what happens when the webhook is called:

A picture containing icon

Description automatically generated

The task chosen here depends on what action we want the GaitAuth-enabled app to trigger. For example, if the device user has a smart lock and wants to unlock their door once they’ve been authenticated by GaitAuth, they can set up a ‘Then That’ to do exactly that. 

This would be particularly useful in a scenario where a parent would like to automatically unlock a house door when their child is coming home from school and approaches the house. There would be no need to remember to bring a key, and there would be no chance of getting locked out. The app, running in the background, can determine when the child is near home, use GaitAuth to verify that the device is being carried by the right person, and call the IFTTT Webhook to unlock the door.

The included sample app triggers an IFTTT Webhook when the device enters a geofenced area surrounding a user-provided address, but it only does so if GaitAuth authentication is successful. It can be used to perform any action that IFTTT is able to trigger – including unlocking a door when a child is nearly home as described above.

Next Steps

Congratulations, you’ve completed our high-level look at how to use GaitAuth and IFTTT together in an iOS app, with a few deeper dives into code at key points. To see what you’ve learned in action, we’ve created a complete sample app that you can find at https://github.com/UnifyID/blog-ios-ifttt

This is just the beginning! While GaitAuth and IFTTT make a great team, just imagine all the places where your iOS apps could benefit from extremely accurate real time authentication based on behavioral biometrics. 

Sign up for a UnifyID developer account at https://developer.unify.id/ and start building ML-powered gait authentication into your apps today.

Unlocking a Password Vault Based on Who You Are, Not What You Have

Security for your digital life is more important than ever. Passwords have been common up until now, but identity and authentication methods are moving away from usernames and passwords. They require users to sacrifice convenience for security and add friction to the overall experience — and many people choose convenience over security due to that friction. 

For instance, if the same password is used for more than one system, then the password being compromised on one system could make the user vulnerable on other systems. 

Password managers, vaults, and multi-factor authentication (MFA) can be useful tools, but much of the time we’re just adding another layer of passwords to remember. Sending authentication codes via SMS or email has been used as an element of MFA processes, but it relies on “what you have” — a device, an email address, or a phone number — and is subject to spoofing or redirection attacks. 

What if we could be even more specific about authentication? Not just what you have, but who you are?

Unique attributes of each person include various aspects of their biometrics, such as their fingerprints or face. While unique, these identifiers might not be available in environments where the user must wear a mask or gloves. Not all devices have biometric support. 

Another way to ensure a person is who they claim to be is by making use of their behavioral biometrics and environmental factors. This type of authentication is passive, or implicit, meaning a user can be authenticated without disruption. It’s also continuous. As a user moves around, the application is able to detect from one moment to the next whether the person carrying the device is the intended user. 

UnifyID offers a novel method of uniquely authenticating using the way you walk. With GaitAuth, your application can provide authentication just by the user carrying a phone as they walk around. In this article, we will show how easy it is to integrate GaitAuth into an Android application.

GaitAuth in an Android App

The GaitAuth SDK lets you easily incorporate machine learning-powered gait authentication into your applications. 

For this article, I created an example of a vault application that stores secrets intended to be accessed by only one user. Since we want to focus on the ease of integrating GaitAuth, the sample just stores simple text secrets like passwords, key strings, or other confidential data. But it could be easily extended to provide one-time passwords (OTP) using a Time-based One-time Password (TOTP) or HMAC-based One-time Password  (HOTP) algorithm. 

The application presents someone with a password challenge, and once the app authenticates the user from either gait data or a correct password, it displays the secrets.

Before integrating GaithAuth into an application, you will need to sign up for a free developer account. Once you have created an account, you will have access to the Developer Dashboard. 

On the Dashboard, next to SDK Keys, click Create. You’ll be asked for a name for identifying the key. Enter the name of your application or some other meaningful label here. After a name is entered and saved, the SDK key will display on the dashboard. You’ll need this key in your mobile app for SDK initialization. For the sample code accompanying this article, place your key in the Android resource file values/secrets.xml into the item named sdkKey.

To add the SDK to the application, a few lines must be added to the project and application build.gradle file. For the project build.gradle, mavenCentral must be added to the buildscript and allprojects sections.

buildscript {
   repositories {
       google()
       jcenter()
      mavenCentral() // add this line
   }
}

allprojects {
   repositories {
       google()
       jcenter()
      mavenCentral() // add this line
   }
}

In the build.gradle for the module, a line must be added to the dependencies section.

dependencies {
   implementation fileTree(dir: "libs", include: ["*.jar"])
   implementation 'androidx.appcompat:appcompat:1.2.0'
   implementation 'androidx.constraintlayout:constraintlayout:2.0.1'
   implementation 'id.unify.sdk:sdk-gaitauth:1.3.13' // add this line
   testImplementation 'junit:junit:4.12'
   androidTestImplementation 'androidx.test.ext:junit:1.1.2'
   androidTestImplementation 'androidx.test.espresso:espresso-core:3.3.0'
}

With these changes, a reference to the UnifyID GaitAuth SDK has been added. 

Some permissions are needed that the application might not already have. Within the application’s AndroidManifest.xml file, add the following permissions. 

<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />

GaitAuth learns how to recognize a user by collecting features from how the person walks. The user should carry the device around for a week so that your application can get to know how the person walks in various situations that may be part of their weekly routine. 

After collecting this feature data, your application will use it to train an ML model for recognizing the user’s steps. A trained model provides a confidence score for the current user being the intended user or for being an imposter. 

Setting Up Feature Collection

The first modification that we want to make to the application is for it to collect features as the user is walking. For collecting features, we place code within an Android service. The service can continue to run and collect features even if the user has navigated to a different application on the device. 

When the service starts, it will initialize the GaitAuth SDK, show a notification to let the user know that it is running, and begin collecting features. 

@Override
public int onStartCommand(Intent intent, int flags, int startId) {
    if(!isInitialized) {
        super.onStartCommand(intent, flags, startId);
        // The username is passed from the activity that starts the service
        userID = intent.getStringExtra(INTENT_USER_ID);
        initGait();
        initNotification();
        isInitialized = true;
    }
    return START_NOT_STICKY;
}

void initGait() {
   UnifyID.initialize(getApplicationContext(), GetSDKKey(), userID, new CompletionHandler() {
    @Override
    public void onCompletion(UnifyIDConfig config) {
        GaitAuth.initialize(getApplicationContext(), config);
        initModel();
    }
    @Override
    public void onFailure(UnifyIDException e) {
        e.printStackTrace();
        postUpdate(e.getMessage());
        Log.e(TAG, e.getMessage());
    }
    });
}

The gait model object is used for recognizing a user by the features of their steps. When a gait model is created, it receives a unique ID string. The ID string should be saved. The ID string can be used to reload the model when the application restarts later. 

void initModel() {
   // If we have not already instantiated a GaitModel, then create one.
    if(gaitModel == null ) {
        // See if there is a GaitModel ID that we can load.
        SharedPreferences pref = getSharedPreferences(
            PREFERENCE_GAITMODEL, MODE_PRIVATE);
        String modelID = pref.getString(PREFERENCE_KEY_MODELID,"");
        GaitAuth gaitAuth = GaitAuth.getInstance();
        try {
            // If there is no modelID, then create a model and save its ID
            if (modelID == "") {
                gaitModel = gaitAuth.createModel();
                SharedPreferences.Editor editor = pref.edit();
                editor.putString(PREFERENCE_KEY_MODELID, gaitModel.getId());
                editor.commit();
            } else {
                // If there is a modelID, then use it to load the model
                gaitModel = gaitAuth.loadModel(modelID);
            }
        } catch (GaitModelException exc) {
            exc.printStackTrace();
       }
    }
}

Training the Model

Since the model hasn’t been trained, it is not able to recognize the user yet. Let’s collect some features to train the model. As new features are generated, they are added to a collection. When the collection reaches a prescribed size, it is saved to device storage. 

final int FEATURES_TO_HOLD = 250;
Vector<GaitFeature> gaitFeatureList = new Vector<GaitFeature>();

void startFeatureCollection() {
    try {
        GaitAuth.getInstance().registerListener(new FeatureEventListener() {
            @Override
            public void onNewFeature(GaitFeature feature) {
                gaitFeatureList.add(feature);
                if(gaitFeatureList.size()>=FEATURES_TO_HOLD) {
                    saveFeatures();
                }
            }
        });
    } catch (GaitAuthException e) {
        e.printStackTrace();
    }
}

The SDK provides methods for serializing and deserializing feature lists to byte data. We will use the static method GaitAuth.serializeFeatures to make a byte stream from the feature list. This byte stream is then written to storage. 

void saveFeatures()  {
    if (gaitFeatureList.size() == 0) {
        return;
    }
    Vector<GaitFeature> featuresToSave = new Vector<GaitFeature>();
    synchronized (gaitFeatureList) {
       featuresToSave.addAll(gaitFeatureList);
       gaitFeatureList.clear();
    }
    try {
        byte[] featureData = GaitAuth.serializeFeatures(featuresToSave);
        File storageFile = getStorageFile(getNextFileSegment());
        FileOutputStream fos = new FileOutputStream(storageFile);
        fos.write(featureData, 0, featureData.length);
        fos.close();
        addFeatureCount(featuresToSave.size());
        notificationBuilder.setContentText(String.format("Saved feature set %d containing %d elements at %s", getFeatureCount(), featuresToSave.size(), new Date()));
        NotificationManager manager = getSystemService(NotificationManager.class);
        manager.notify(1, notificationBuilder.build());
    } catch (FeatureCollectionException | FileNotFoundException exc) {
        exc.printStackTrace();
    } catch (IOException exc) {
        exc.printStackTrace();
    }
}

Once there are enough features, we can initiate training. UnifyID recommends a minimum of three days and 7,000 walk cycles, but suggests using seven days and 10,000 walk cycles for optimal training.

In the sample program, a button on the settings screen starts the training. 

To train the model, we deserialize the features that have been collected and input them into our model using the add method. After the features are added, we call GaitModel.train. Training can take a few hours. GaitModel.getStatus gets the status of the model. The function returns one of the following values:

  • CREATED – the model hasn’t yet been trained.
  • TRAINING – training is in process. Check again later for the training result.
  • READY – the model is trained and ready to begin recognizing users
  • FAILED – the model could not be trained. 

If training fails, GaitModel.getReason returns a string that explains why the failure occurred. Attempting to train the model with a tiny data set results in a message stating that the amount of training data is insufficient. When the function returns READY, we can begin using it to authenticate the user. 

Authenticating the User

For a model that is ready, there are two methods of evaluating this data to determine if a device is in the hands of the intended person. 

One method is to examine the gait feature score. Possible scores range from -1.0 to 1.0. 

Positive scores indicate the current user is the person whose walking patterns were used to train the model. 

Negative scores indicate the person holding the device is an imposter. 

Your organization may want to evaluate different thresholds for acceptance to find one that is acceptable. A passing score of 0.6 to 0.8 is a good starting point. 

In the following code, the scores of the last four features collected are averaged together. If the most recent feature was collected within the past 60 seconds and the average is greater than 0.6, then the user is considered authenticated.

static final float PASSING_SCORE = 0.6f;
static final long  MAX_PASSING_AGE = 30000;
static final int MIN_SCORE_COUNT = 4;

public boolean isAuthenticated() {
    if(gaitScoreList.size()>=MIN_SCORE_COUNT) {
        long age = (new Date()).getTime() - gaitFeatureList.get(gaitFeatureList.size()-1).getEndTimeStamp().getTime();
        float sum = 0.0f;
        for(GaitScore score:gaitScoreList) {
            sum += score.getScore();
        }
        float avg = sum / (float)gaitScoreList.size();
        if(avg > PASSING_SCORE && age <=MAX_PASSING_AGE) {
            return true;
        }
    }
    return false;
}

When examining the feature scores to authenticate the user, there is freedom for deciding if a user will be authenticated or not for certain scenarios. 

There is also a much easier way to authenticate a user. The GaitAuth SDK provides an authenticator that can collect features and perform authentication for you. 

To create a GaitAuth authenticator, first create a configuration. The configuration contains settings for the maximum age of features to consider, setting a threshold for a passing feature, and other attributes that affect how the features are evaluated.

GaitQuantileConfig config = new GaitQuantileConfig(QUANTILE_THRESHOLD);
config.setMinNumScores(1);    // Require at least 1 score
config.setMaxNumScores(50);   // Set the maximum number of scores to use for authentication
config.setMaxScoreAge(10000); // Set the maximum age, in milliseconds, for features
config.setNumQuantiles(100);  // Set the number of quantiles (divisions) for the feature data
config.setQuantile(50);

Once created, the authenticator continues to collect information from the user’s walking. The authentication status can be checked at any time by calling getStatus() on the authenticator. The call to getStatus() accepts an  AuthenticationListener. Either the onCompletion or onFailure method on this object will be called. 

Note that if onCompletion is called, that does not imply that the user was authenticated. A call to onCompletion means that the authenticator was able to perform an evaluation. To determine if the user is authentic, check isAuthenticated.

gaitAuthenticator.getStatus(new AuthenticationListener() {
   @Override
   public void onComplete(AuthenticationResult result) {
       gaitAuthenticatorResult = result.getStatus();
              
       switch(result.getStatus())
       {
           case AUTHENTICATED:
               isAuthenticated = true;
           break;
           case UNAUTHENTICATED:
               isAuthenticated = false;
           Default:
	     break;
       }
   }
   @Override
   public void onFailure(GaitAuthException cause) {

   }
});

The authenticator will continue to authenticate the user in the background. 

The application unlocks the stored secrets when it detects the user recently walked and that it was an authorized user. If the application cannot authenticate the user from their walk (the user hasn’t recently walked), the password unlock feature is available as a fallback.

Next Steps

We now have a password vault application that is able to recognize a user by the way that they walk. We did this by adding the GaitAuth SDK to the project, collecting features based on the user’s gait, and using the features to train a model to recognize the user. The application unlocks for the user when the trained model recognizes their gait. As noted earlier, we can easily change the application functionality to add features like one-time passwords.

You can read more about the GaitAuth SDK at UnifyID’s documentation site. Sign up for free on the developer dashboard to begin testing with the SDK. For a more in-depth look at how gait biometric verification works, see this publication on the UnifyID site. You can download the sample application used in this blog post from https://github.com/UnifyID/blog-android-secrets.

Integrating GaitAuth™ into Your Android App

GaitAuth™ is an SDK offered by UnifyID that allows you to authenticate your users based on how they move. This post demonstrates the process of adding GaitAuth to a simple Android app.

The UnifyID Developer Portal has high-level documentation that covers the basics of the GaitAuth SDK integration process. There are also auto-generated JavaDocs available for the specific details. The goal of this post is to meet the two in the middle and give some more color to the integration process. By the end of the post we’ll have built a sample Android app that uses GaitAuth to train and test a GaitModel. Along the way, we’ll also explore relevant best practices and important implementation details.

The Sample App

All of the sample app code is available on GitHub. To get a feel for the training and testing process you can build the app on your phone and try it for yourself. If you want to get right to building your own app, you can treat the repository as a collection of helpful code snippets. You can also use the code to follow along with this post in depth. Not all of the code is shown in this post, the code that is shown has been abbreviated for simplicity’s sake. Links to the original code on GitHub are provided at the top of the snippets.

The sample app closely mirrors the functionality of the GaitAuth SDK. On the starting screen you are presented with the option to create or load a model. You’ll want to create a new model when you first use the app. In future uses, you can use the load option to skip training. After creating a model you’re ready to collect data and train the model. First, turn on collection (it will continue to collect even if the phone is locked or the app is backgrounded or closed). Once you’ve collected some features you can add them to the model. After you’ve collected enough data you can train the model. While you wait for the model to train (which may take a few hours), you can manually refresh its status.

If the model fails to train you’ll need to start over by pressing the trashcan icon in the top left corner. When the model successfully trains you’re ready to test it. Turn on feature collection and walk around for a while. When you are ready, stop collecting features and score them. This will graph the scores and show you an authentication decision.

Now that we know what the sample app does, let’s go build it.

Configuration & Initialization

Adding GaitAuth to our Gradle configuration is a good starting point. We’ll also need to request some permissions in the Android Manifest. We can follow the steps outlined in the Developer Portal documentation to take care of that.

Before the GaitAuth SDK can be used anywhere in the app it must be initialized. The initialization is trivial; always initializing it before using it is harder. In something straightforward like this sample app we can simply initialize it in the onCreate method of the MainActivity.

// https://github.com/UnifyID/gaitauth-sample-app-android/blob/470932205438dd2ce43dc6bad586df90c72cc800/app/src/main/java/id/unify/gaitauth_sample_app/MainActivity.java#L144
if (GaitAuth.getInstance() == null) {
    // First initialize the UnifyID Core SDK
    UnifyID.initialize(getApplicationContext, SDK_KEY, USER, new CompletionHandler() {
        @Override
        public void onCompletion(UnifyIDConfig config) {
            // Second initialize the GaitAuth SDK
            GaitAuth.initialize(context, config);
            // Save these values for debugging purposes
            Preferences.put(Preferences.CLIENT_ID, config.getClientId());
            Preferences.put(Preferences.INSTALL_ID, config.getInstallId());
            Preferences.put(Preferences.CUSTOMER_ID, config.getCustomerId());
            startGaitAuthService(context);
            route();
        }
    });
}

When initialization succeeds we squirrel away a couple of relevant details in the Shared Preferences (the Preferences class hides the idiosyncrasies of the Shared Preferences API). These will come in handy for debugging. You can view them by tapping on the info icon in the top right corner of the sample app. We also start a foreground service — more on this later. Finally, we call route which determines what the app does next.

In an app with a more complex workflow, initialization of the GaitAuth SDK may not be so simple. In these scenarios we recommend you wrap the SDK in a class that protects its usage. With some simple synchronization this wrapper can ensure that the SDK is never used uninitialized.

Two important points remain. First, remember that the SDK key is a sensitive value and should be protected. In the sample app we ask the user to enter the SDK key the first time they use the app. For an app in production, something like Android Keystore can be used. Second, the user value has a few important stipulations on it. It must be unique, immutable, and should be unrelated to any personally identifiable information. We don’t recommend using things like email addresses or phone numbers for the user value.

The GaitModel

Now that we’ve gotten through the drudgery of initialization it’s time to talk about the star of the show — the GaitModel. In a sense the sample app can be viewed as a tool for managing the lifecycle of a GaitModel. It creates a new model, loads training data into it, initiates training, and then tests the model. For this reason, the sample app’s routing is based on the status of the current GaitModel.

The sample app uses a single-activity/multiple-fragment architecture where each fragment is a different screen. In the MainActivity after the initialization of the GaitAuth SDK the following routing code is run.

// https://github.com/UnifyID/gaitauth-sample-app-android/blob/470932205438dd2ce43dc6bad586df90c72cc800/app/src/main/java/id/unify/gaitauth_sample_app/MainActivity.java#L185
private void route() {
    // Load the id of the current GaitModel
    String modelId = Preferences.getString(Preferences.MODEL_ID);
    if (Strings.isNullOrEmpty(modelId)) {
        showFragment(new SelectModelFragment());
    } else {
        loadModel(modelId);
    }
}

// https://github.com/UnifyID/gaitauth-sample-app-android/blob/470932205438dd2ce43dc6bad586df90c72cc800/app/src/main/java/id/unify/gaitauth_sample_app/MainActivity.java#L287
private void loadModel(String modelId) {
    AsyncTask.execute(() -> {
        model = GaitAuth.getInstance().loadModel(modelId);
        Preferences.put(Preferences.MODEL_ID, modelId);
        renderFragmentBasedOnModelStatus(model.getStatus());
    });
}

// https://github.com/UnifyID/gaitauth-sample-app-android/blob/470932205438dd2ce43dc6bad586df90c72cc800/app/src/main/java/id/unify/gaitauth_sample_app/MainActivity.java#L255
private void renderFragmentBasedOnModelStatus(GaitModel.Status status) {
    switch (status) {
        case CREATED:
            showFragment(FeatureCollectionFragment.build(gaitAuthService.isTraining()));
            break;
        case TRAINING:
            showFragment(new ModelPendingFragment());
            break;
        case FAILED:
            showFragment(ModelErrorFragment.newInstance(model.getReason()));
            break;
        case READY:
            showFragment(TestingFragment.build(gaitAuthService.isTesting()));
            break;
        default:
            // treat it as a failure
            showFragment(ModelErrorFragment.newInstance("unknown model status"));
            break;
    }
}

First the method route looks for the id of the current GaitModel and asynchronously loads it with the help of loadModel. After the model is loaded, renderFragmentBasedOnModelStatus is called. A simple switch statement then sends the user to the screen matching the current state of the model.

The method route will not find a model id on a user’s first time through the app or if the reset button was pressed. In these cases the user is immediately sent to the SelectModelFragment. From here, when the user clicks on the “Create Model” button, onCreateModelPressed is executed. It builds a new GaitModel, saves the model id in the shared preferences, and sends the user to the FeatureCollectionFragment. Alternatively, the user can opt to load a pre-existing model which leverages the same loadModel method.

// https://github.com/UnifyID/gaitauth-sample-app-android/blob/470932205438dd2ce43dc6bad586df90c72cc800/app/src/main/java/id/unify/gaitauth_sample_app/MainActivity.java#L315
public void onCreateModelPressed() {
    AsyncTask.execute(() -> {
        model = GaitAuth.getInstance().createModel();
        Preferences.put(Preferences.MODEL_ID, model.getId());
        showFragment(new FeatureCollectionFragment());
    });
}

Feature Collection

So we have a GaitModel locked and loaded, but now what? The model is useless without training data so let’s start there. A GaitModel is trained on a collection of GaitFeatures which are data points collected from the user’s movement. These GaitFeatures are given to the model via the add method which has the signature void GaitModel.add(Collection<GaitFeature> features). Later during training, only the features explicitly added to the model will be used.

Now that we know how to use the features, how do we actually collect them? This is achieved by registering a FeatureEventListener that will fire the onNewFeature callback for every feature collected. Correctly managing feature collection requires tackling two key issues: feature storage and backgrounding.

Storing Features

In a naive implementation of feature collection, every time a new feature was received it would be immediately added to the GaitModel. There are two problems with this. First, adding features to the GaitModel may use network resources or trigger other expensive operations and thus is inefficient to call frequently. Second, if the model fails when training you will need to recollect all new data for the new model since you didn’t persist it anywhere.

The sample app solves the feature storage problem with a thread-safe FeatureStore class. This class exposes a method with the signature void add(GaitFeature feature), which serializes the feature and appends it to a file on disk. At a future time (when the user clicks the “Add Feature” button) all of the features can be loaded from disk, deserialized and returned via the method getAll with the signature List<List<GaitFeature>> getAll(). Note that it returns the features partitioned into multiple lists. This is because adding thousands of features to a model at once should be avoided. Finally, there is an empty method to clear the file after adding features. This prevents adding features twice. Deleting the features after using them reintroduces the persistence problem though. The sample app does it anyways to avoid re-adding features to the model in a simple manner.

// https://github.com/UnifyID/gaitauth-sample-app-android/blob/470932205438dd2ce43dc6bad586df90c72cc800/app/src/main/java/id/unify/gaitauth_sample_app/GaitAuthService.java#L163
public void onNewFeature(GaitFeature feature) {
    featureStore.add(feature);
    int count = Preferences.getInt(Preferences.FEATURE_COLLECTED_COUNT) + 1;
    Preferences.put(Preferences.FEATURE_COLLECTED_COUNT, count);
}

// https://github.com/UnifyID/gaitauth-sample-app-android/blob/470932205438dd2ce43dc6bad586df90c72cc800/app/src/main/java/id/unify/gaitauth_sample_app/MainActivity.java#L363
public int onAddFeaturesPressed() {
    FeatureStore featureStore = FeatureStore.getInstance(this);
    List<List<GaitFeature>> chunks = featureStore.getAll();
    int uploadedCounter = 0;

    for (List<GaitFeature> chunk: chunks) {
        model.add(chunk);
        uploadedCounter += chunk.size();
    }
    if (uploadedCounter > 0) { // only truncate file after we uploaded something
        featureStore.empty();
    }
    return uploadedCounter;
}

In a production application there are many improvements you would want to make to FeatureStore. First and foremost, it should implement some form of in-memory buffering. Writing to disk for every feature you collect is slow and can lead to poor battery-life. Second, it should rotate files to avoid size limitations and corruption. Third, it should not clear the file after adding the features to the model. Rather, it should keep track of what features have been added and only add the new ones.

Backgrounding

The second key issue to solve for feature collection is backgrounding. It would not be wise to register the FeatureEventListener on the app’s main thread. As soon as the user closed the app, GaitFeatures would no longer be collected. Android services can help us solve this problem. Services provide a way to execute a long-running operation in the background. There are two relevant types of Android services: background and foreground. A background service needn’t provide any indication to the user that it is running, but is more likely to be shut down by the OS if resources are scarce. A foreground service must present a notification to the user indicating its presence the entire time it is alive. But, it is unlikely to be killed by the OS.

The sample app takes the most straightforward approach. In the onCreate method of the MainActivity a foreground service is created regardless of whether or not the service will be used. This avoids complex state management and synchronization issues that arise when dynamically building a service. In the onCreate method the activity binds to the service. And in the onStop method it unbinds from the service. This gives the activity direct access to the feature collection service.

// https://github.com/UnifyID/gaitauth-sample-app-android/blob/470932205438dd2ce43dc6bad586df90c72cc800/app/src/main/java/id/unify/gaitauth_sample_app/MainActivity.java#L104
protected void onStop() {
    super.onStop();
    if (gaitAuthServiceBound.get()) {
        unbindService(gaitAuthServiceConnection);
        gaitAuthServiceBound.set(false);
    }
}

You may want to handle services differently in a production app. For example, you may only want to start the service when you are actually collecting features. If you go this route make sure to take special care in synchronizing the usage of the GaitAuth SDK.

Final Considerations

That was a lot of details. Let’s take a step back for a moment and consider the entire training process. Feature collection for training is the most critical stage for the GaitAuth SDK. To get good authentication results you need to have a well trained model. The Developer Portal documentation has a number of suggestions on how to best do this.

Training the Model

The hard work of feature collection was well worth the effort. We now have a plethora of GaitFeatures to train with. We’re nearly ready to use our GaitModel, but first we need to train it. Thankfully, training is easy. When a user clicks on the “Train Model” button the method below is called. In a background thread it kicks off the training process for the model and sends the user to the ModelPendingFragment.

// https://github.com/UnifyID/gaitauth-sample-app-android/blob/470932205438dd2ce43dc6bad586df90c72cc800/app/src/main/java/id/unify/gaitauth_sample_app/MainActivity.java#L397
public void onTrainModelPressed() {
    AsyncTask.execute(() -> {
        try {
            model.train();
            showFragment(new ModelPendingFragment());
        } catch (GaitModelException e) {
            showToast("Failed to start training model.");
        }
    });
}

At the pending model screen a user can manually refresh the status of a model while they wait for it to train.

// https://github.com/UnifyID/gaitauth-sample-app-android/blob/470932205438dd2ce43dc6bad586df90c72cc800/app/src/main/java/id/unify/gaitauth_sample_app/MainActivity.java#L436
public void onRefreshPressed() {
    AsyncTask.execute(() -> {
        try {
            model.refresh();
            renderFragmentBasedOnModelStatus(model.getStatus());
        } catch (GaitModelException e) {
            showToast("Failed to refresh model status.");
        }
    });
}

After refreshing the status of the model, our old friend renderFragmentBasedOnModelStatus is called to bring the user to the right screen given the model’s status. If the training failed for some reason the ModelErrorFragment will load. From there the user has no choice other than to reset and start over. After a successful training, the user will be presented with the TestingFragment. And of course, if the model status is still TRAINING after a refresh then no navigation will occur.

Testing the Model

The hard work is over now — we’ve trained a GaitModel and can now reap the benefits. All of the testing functionality is managed by the Authenticator interface. When you instantiate an Authenticator you pass it a GaitModel and a scoring policy. Once created, it automatically starts collecting features. You can ask it for an authentication decision at any time and it will say if the user is authenticated or unauthenticated. In the scenario where this is not enough data to make a decision it will return inconclusive. When the user presses the “Start Collection” button onStartCollectionBtnPressed is called. It in turn tells the foreground service to create a new Authenticator object.

// https://github.com/UnifyID/gaitauth-sample-app-android/blob/470932205438dd2ce43dc6bad586df90c72cc800/app/src/main/java/id/unify/gaitauth_sample_app/MainActivity.java#L338
public void onStartCollectionBtnPressed() {
    try {
        gaitAuthService.startFeatureCollectionForTesting(model);
    } catch (GaitAuthException e) {
        showToast("Failed to start feature collection for testing.");
    }
}

// https://github.com/UnifyID/gaitauth-sample-app-android/blob/470932205438dd2ce43dc6bad586df90c72cc800/app/src/main/java/id/unify/gaitauth_sample_app/GaitAuthService.java#L213
public void startFeatureCollectionForTesting(GaitModel model) throws GaitAuthException {
    GaitQuantileConfig config = new GaitQuantileConfig(QUANTILE_THRESHOLD);
    authenticator = GaitAuth.getInstance().createAuthenticator(config, model);
}

A quick aside on the GaitQuantileConfig policy and how it works. In short it will authenticate the user if at least X percent of scores in the session scored Y or more (learn more about scores here). X is known as the quantile and Y is the score threshold. GaitQuantileConfig sets the quantile to 50% by default and in the sample app the score threshold is set to 0.8. The table below shows three example sessions with these numbers. The first session has 60% of scores at or above the 0.8 score threshold, and therefore has an authenticated result. However, the second and third sessions only have 40% and 20% of scores that meet the 0.8 score threshold, and therefore they produce an unauthenticated result.

You can customize more than just the quantile and score threshold of the GaitQuantileConfig. The method setMinNumScores lets you configure how many scores are required for an authentication decision to be made. Any attempt to authenticate with a number of scores less than this minimum will return inconclusive. Similarly, setMaxNumScores configures the maximum amount of scores that will be considered. If there are more scores than the maximum, the most recent scores will be chosen. Finally, setMaxScoreAge determines how old of scores can be used. Scores older than the given age will not be used for an authentication decision.

Back to the action. The sample app requires the user to stop collecting features before they can score them. Note that this is not a requirement of the GaitAuth SDK and is only done to simplify state management. The Authenticator has a stop method which helps us do this. Clicking the “Stop Collection” button kicks off this sequence of events.

// https://github.com/UnifyID/gaitauth-sample-app-android/blob/470932205438dd2ce43dc6bad586df90c72cc800/app/src/main/java/id/unify/gaitauth_sample_app/MainActivity.java#L349
public void onStopCollectionBtnPressed() {
    gaitAuthService.stopFeatureCollectionForTesting();
}

// https://github.com/UnifyID/gaitauth-sample-app-android/blob/470932205438dd2ce43dc6bad586df90c72cc800/app/src/main/java/id/unify/gaitauth_sample_app/GaitAuthService.java#L223
public void stopFeatureCollectionForTesting() {
    if (authenticator != null) {
        authenticator.stop();
    }
}

Now the user can press the “Score Features” button. This entails getting the authenticator from the foreground service and then getting an authentication status from the authenticator. Then it sends the user to the ScoreFragment. The authenticator also returns the individual scores that lead to the authentication decision. ScoreFragment puts these in a graph to help visualize the decision. How you use the authenticator will be highly dependent on the specifics of your use case.

// https://github.com/UnifyID/gaitauth-sample-app-android/blob/470932205438dd2ce43dc6bad586df90c72cc800/app/src/main/java/id/unify/gaitauth_sample_app/MainActivity.java#L469
public void onScoreFeaturesPressed() {
    Authenticator authenticator = gaitAuthService.getAuthenticator();
    
    authenticator.getStatus(new AuthenticationListener() {
        @Override
        public void onComplete(AuthenticationResult authenticationResult) {
            showFragment(scoreFragment);
        }

        @Override
        public void onFailure(GaitAuthException e) {
            showToast("Failed to get scores.");
        }
    });
}

Conclusion

And just like that we’ve integrated GaitAuth into a simple Android application. For more implementation details you can explore the code in depth on GitHub. If you build something with GaitAuth, let us know on social media. We’d love to hear about it. Finally, reach out to us if you have any trouble integrating.