Passwordless Authentication With Account Kit

Passwordless authentication skips using a password for registration or login. Instead, user authentication is confirmed either with a one-time SMS verification code sent to the user’s phone or a one-time link to their email address.

Passwordless Authentication With Account Kit

Why Use Passwordless Authentication?

  • Seamless login and registration process for your users.
  • Keeps access to your app secure, because the user will not reuse passwords or resort to easily guessed passwords (such as “password”).
  • Avoids taxing your users with the need to create and remember unique passwords

In this quick tip tutorial, I will show you how to use Account Kit by Facebook for passwordless authentication in your Android app. Your users will register and login with either their phone number or an email address. Users don’t even need to have a Facebook account to be authenticated.

Not only that, but Account Kit is easy to implement and saves you from having to tediously build a login system.

Passwordless Authentication With Account Kit

How Does Account Kit Work?

The following diagram should make clear how Account Kit works.

Passwordless Authentication With Account Kit

The authentication takes place in a series of exchanges between the user and app. First the user initiates the login, perhaps by loading the app on their phone. Then, a verification code is sent to the user’s SMS, or a one-time link is sent by email. After that, if the user enters the validation code or clicks the link, they will be authenticated for the app.

Another cool feature of Facebook Account Kit is that when your user enters his or her phone number into the app, Account Kit will make an attempt to match it with the phone number connected to the user’s Facebook profile. If the user is logged into the Android Facebook app, and the phone numbers match, Account Kit will skip sending the SMS verification code and the user will be logged in more seamlessly.

Using Account Kit

1. Prerequisites

To begin to use Account Kit, you’ll need:

2. Enable Account Kit

Go to your app dashboard, click the Add Product button, and select Account Kit. Then click the Get Started button to add Account Kit. What you will see is the settings configuration for Account Kit.

Passwordless Authentication With Account Kit

3. Declare Dependencies

Add the dependency with the latest version of the Account Kit SDK in your build.gradle file and sync your project.

repositories {
  jcenter()
}

dependencies {
  compile 'com.facebook.android:account-kit-sdk:4.+'
}

4. Update AndroidManifest.xml

Add your Facebook app ID, Account Kit client token (this is available on the Account Kit settings dashboard), and the INTERNET permission to the AndroidManifest.xml.

<uses-permission android:name="android.permission.INTERNET" />
<meta-data android:name="com.facebook.accountkit.ApplicationName"
           android:value="@string/app_name" />
<meta-data android:name="com.facebook.sdk.ApplicationId"
           android:value="@string/FACEBOOK_APP_ID" />
<meta-data android:name="com.facebook.accountkit.ClientToken"
           android:value="@string/ACCOUNT_KIT_CLIENT_TOKEN" />

<activity
  android:name="com.facebook.accountkit.ui.AccountKitActivity"
  android:theme="@style/AppLoginTheme"
  tools:replace="android:theme"/>

5. Update the Resource Files

Include your app id and Account Kit client token in your strings.xml file.

<string name="FACEBOOK_APP_ID">YourAPPId</string>
<string name="ACCOUNT_KIT_CLIENT_TOKEN">YourAccountKitClientToken</string>

Also include the Account Kit theme in your styles.xml.

<style name="AppLoginTheme" parent="Theme.AccountKit" />

6. Initialize the SDK

In your Application class, initialize the SDK (remember to include the android:name in your AndroidManifest.xml).

public class MyApplication extends Application {

    @Override
    public void onCreate() {
        super.onCreate();
        AccountKit.initialize(getApplicationContext());
    }
}

7. Initiate the Login Flow

We have to write a separate handler for the SMS and email login authentication flows.

For SMS, on line 5, we specify the login type LoginType.PHONE.

public void onSMSLoginFlow(View view) {
    final Intent intent = new Intent(this, AccountKitActivity.class);
    AccountKitConfiguration.AccountKitConfigurationBuilder configurationBuilder =
            new AccountKitConfiguration.AccountKitConfigurationBuilder(
                    LoginType.PHONE,
                    AccountKitActivity.ResponseType.CODE); // or .ResponseType.TOKEN
    // ... perform additional configuration ...
    intent.putExtra(
            AccountKitActivity.ACCOUNT_KIT_ACTIVITY_CONFIGURATION,
            configurationBuilder.build());
    startActivityForResult(intent, 101);
}

For email, on line 5, we specify the login type LoginType.EMAIL.

public void onEmailLoginFlow(View view) {
    final Intent intent = new Intent(this, AccountKitActivity.class);
    AccountKitConfiguration.AccountKitConfigurationBuilder configurationBuilder =
            new AccountKitConfiguration.AccountKitConfigurationBuilder(
                    LoginType.EMAIL,
                    AccountKitActivity.ResponseType.CODE); // or .ResponseType.TOKEN
    // ... perform additional configuration ...
    intent.putExtra(
            AccountKitActivity.ACCOUNT_KIT_ACTIVITY_CONFIGURATION,
            configurationBuilder.build());
    startActivityForResult(intent, 101);
}

8. Lay Out the Login Screen

Here’s a simple layout for a screen that shows buttons to log in with SMS or email.

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
        xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:tools="http://schemas.android.com/tools"
        android:id="@+id/activity_main"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:paddingLeft="@dimen/activity_horizontal_margin"
        android:paddingRight="@dimen/activity_horizontal_margin"
        android:paddingTop="@dimen/activity_vertical_margin"
        android:paddingBottom="@dimen/activity_vertical_margin"
        android:orientation="vertical"
        tools:context="com.chikeandroid.tutsplus_facebook_accountkit.MainActivity">

    <Button
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text="Login By SMS"
            android:onClick="onSMSLoginFlow"/>

    <Button
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text="Login By Email"
            android:onClick="onEmailLoginFlow"/>
</LinearLayout>

9. Handle Responses From the Login Flow

Now when a user attempts to log in, we’ll get a response in the onActivityResult() method. In this method, we can handle successful, cancelled, and failed authentications.

@Override
protected void onActivityResult(final int requestCode, final int resultCode, final Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
    
    if (requestCode == 101) { // confirm that this response matches your request
        AccountKitLoginResult loginResult = data.getParcelableExtra(AccountKitLoginResult.RESULT_KEY);
        String toastMessage;
        if (loginResult.getError() != null) {
            toastMessage = loginResult.getError().getErrorType().getMessage();
            showErrorActivity(loginResult.getError());
        } else if (loginResult.wasCancelled()) {
            toastMessage = "Login Cancelled";
        } else {
            if (loginResult.getAccessToken() != null) {
                toastMessage = "Success:" + loginResult.getAccessToken().getAccountId();
            } else {
                toastMessage = String.format(
                        "Success:%s...",
                        loginResult.getAuthorizationCode().substring(0, 10));
            }

            // If you have an authorization code, retrieve it from
            // loginResult.getAuthorizationCode()
            // and pass it to your server and exchange it for an access token.

            // Success! Start your next activity...
            goToMyLoggedInActivity();
        }

        // Surface the result to your user in an appropriate way.
        Toast.makeText(this, toastMessage, Toast.LENGTH_LONG).show();
    }
}

The Completed App

Now we can run our app to test the SMS and email login flows!

Passwordless Authentication With Account Kit

Note that the Account Kit JavaScript SDK doesn’t support WebView login, so you can’t log people in from a WebView with Account Kit. You’ll have to write your Account Kit login interface with native code.

Conclusion

In this quick tip tutorial, you learned about passwordless authentication using Facebook Account Kit: what it is, why you might want to consider using it, and how to implement it in your Android app.

A word of warning, though: some see passwordless authentication as less secure. Most people wouldn’t use it when security is a priority, for example with a banking app. So use some discretion about when to use it and when to go with a more traditional authentication scheme.

To learn more about Facebook Account Kit, refer to the official documentation. And to learn more about Android development, check out some of our other posts here on СodeHolder Tuts+!

  • Passwordless Authentication With Account Kit

    Communication Within an Android App With EventBus

    Greenrobot EventBus is a popular open-source library that uses the publish/subscribe model for communication between components of the Android system. In…
  • Passwordless Authentication With Account Kit

    Firebase for Android: File Storage

    During the 2016 Google I/O conference, Firebase was reintroduced to the developer community as a major resource for providing quick back-end support for web…
  • Passwordless Authentication With Account Kit

    How to Create an Android Chat App Using Firebase

    With Firebase, creating real-time social applications is a walk in the park. And the best thing about it is that you don’t have to write a single line of…
  • Passwordless Authentication With Account Kit

    Coding Functional Android Apps in Kotlin: Lambdas, Null Safety & More

    The Kotlin language for Android apps lets you do coding that would either be much more verbose in Java or not possible to achieve with Java alone. Learn how…