Using reCAPTCHA in Android with SafetyNet API, LiveData, ViewModel and Retrofit

Prasannajeet Pani
Android Nuggets
Published in
4 min readSep 5, 2018

Away with the bots!

Google’s SafetyNet API provides a collection of services that help shield Android applications from a plethora of hazards that plague the online world in this day and age, viz. compromised devices, security threats, harmful websites, phishing attacks, malware apps and bots.

Among the many services that SafetyNet API offers is the ability to verify the authenticity (human/bot) of a user via a reCAPTCHA in order to prevent applications, especially ones where one need to perform user registrations, from being inundated with bots.

I had a really hard time searching the Internet trying to find an article that is updated with the latest SafetyNet API, LiveData, ViewModel and Retrofit. So once I finished with the code, I decided to write one myself.

The SafetyNet reCAPTCHA API has a 2-step verification process

  1. A device-side verification with the Site Key generating a user response token.
  2. A server-side verfication using the response token from 1 and the Secret Key

In this article, we go through the steps that adds a reCAPTCHA into an Android app and validates the user.

Step 1: Terms & Conditions

T&Cs of using Google APIs for the fine-print-junkie

Step 2: Register App & Get Site & Secret Keys

In order to use SafetyNet reCaptcha API, first we register the Android application on the reCaptcha Android sign-up site. We enter a label and the app’s applicationID in the form below:

One we fill out the form and click on Register we will be provided with a Site Key and a Secret Key. The Site Key is used to verify the request while the Secret Key verifies the user response via a service call. It is advised to securely store the keys in your application.

Step 3: Setup The Module build.gradle

In our module level build.gradle we add a few dependencies required to perform the entire verifcation process.

First, the play-services-safetynet dependency.

implementation 'com.google.android.gms:play-services-safetynet:15.0.1'

Also, the Retrofit dependencies for response verification

implementation 'com.squareup.retrofit2:retrofit:2.3.0'
implementation 'com.squareup.retrofit2:converter-gson:2.3.0'

Optional: I used Android Architecture Component’s LiveData and ViewModel in my sample app for which I added the below dependency.

implementation "android.arch.lifecycle:extensions:$lifecycle_version"

Step 4: Request Verification Using Site Key

Wherever in the Android application we would perform the reCAPTCHA verifcation, we have to instantiate the SafetNet API and add a success and a failure listener and invoke the verifyWithRecaptcha method.

SafetyNet.getClient(MainActivity.this).verifyWithRecaptcha(**SITE KEY GOES HERE**)
.addOnSuccessListener(new SuccessListener())
.addOnFailureListener(new FailureListener());

Instead of using anonymous inner classes I chose to use concrete implementations. Below is the FailureListener class.

We will see how our SuccessListener class looks in the next step

Step 5: Response Verification Using Secret Key

If the device-side verfication goes well, we need to perform a secondary verification via a webservice. For that purpose, we need to send a POST request to the URL: https://www.google.com/recaptcha/api/siteverify with following three parameters:

Query parameters for response verification

For the purpose of simplicity, we will skip sending the remoteip parameter

This task is performed by our SuccessListener class which is an implementation of the onSuccessListener interface provided by SafetyNet API.

Before we see the class, let’s set up our Retrofit to perform the network call required for the verification. In order to set up the service we need a Retrofit API interface as shown below

API class

Note: Even though the service is a POST request, the parameters have to be passed as query parameters more commonly seen in GET requests

Next, we set up the service. I have used a Repository pattern and a ViewModel for modularity purposes.

Repository class

The RecaptchaVerificationResponse is our response POJO class that gson uses to de-serialize the JSON response from the service call

{
"success": true|false,
"challenge_ts": timestamp, // timestamp of the challenge load
"apk_package_name": string, // the package name of the app
"error-codes": [...] // optional
}
Response Object

And finally, below is our SuccessListener which performs the entire token response verification and observes our ViewModel.

And thats it! If done correctly, the device and the service verification will complete successfully and the user will be verified to be not a bot.

Github repo for the app built for this tutorial

Liked the article? Well slap on those claps!

Questions? -> Twitter

--

--

Prasannajeet Pani
Android Nuggets

Android Developer to fund my Photography to feed my soul. My alter ego is a stand-up comedian. IG: http://instagram.com/prasan.photos