How to Integrate Google reCAPTCHA in Android?


To enhance security and prevent unauthorized access by automated bots, integrating Google reCAPTCHA into an Android application becomes crucial. By incorporating reCAPTCHA, developers can effectively verify the authenticity of users, thereby reducing the potential risks associated with spam, abuse, and fraudulent activities.

The process for reinforcing app security and providing a seamless user experience involves three steps. First, the Android developer obtains API keys from Google reCAPTCHA. Next, they integrate the reCAPTCHA functionality into the user interface of their Android app. Finally, they validate user responses to ensure successful reCAPTCHA verification. By incorporating Google reCAPTCHA, Android developers can enhance app security and create a protected environment for genuine users.

Google reCAPTCHA

Google reCAPTCHA, provided by Google, is a widely used security service that safeguards websites and applications against automated bots and malicious activities. It presents users with challenges like image recognition or checkbox verification to determine their human authenticity. By incorporating reCAPTCHA, developers can enhance platform security, reduce spam and abuse, and ensure a safer and more reliable user experience.

Approaches

There are two different methods to integrate Google reCAPTCHA in an Android app:

  • Using reCAPTCHA API with WebView

  • Using reCAPTCHA API with SafetyNet API (Without WebView)

Both methods essentially accomplish the same goal of integrating Google reCAPTCHA into an Android app, but the first method involves using a WebView to load the reCAPTCHA API, while the second method directly utilizes the SafetyNet API for verification without relying on a WebView.

Using reCAPTCHA API with WebView

In this method, developers can create a WebView within their Android app specifically designed to load the reCAPTCHA API. By configuring the WebView to enable JavaScript and loading the designated reCAPTCHA URL, they ensure seamless integration. To handle the response from re-CAPTCHA, developers implement a WebViewClient and override the shouldOverrideUrlLoading function.

Within the custom implementation of handleRecaptchaResponse, they extract the re-CAPTCHA response token directly from the URL. Using the SafetyNet API, developers then verify the validity of this token for added security measures. Successful validation grants them access to perform desired actions within their application.

Algorithm

  • Create a WebView and enable JavaScript.

  • Load the reCAPTCHA API URL in the WebView.

  • Implement a WebViewClient and override shouldOverrideUrlLoading.

  • Inside shouldOverrideUrlLoading, extract the reCAPTCHA response token from the URL.

  • Use the SafetyNet API to verify the response token's validity.

  • If the validation succeeds, perform the desired actions in your app.

Example

import android.annotation.SuppressLint;
import android.os.Bundle;
import android.webkit.WebResourceRequest;
import android.webkit.WebView;
import android.webkit.WebViewClient;

import androidx.appcompat.app.AppCompatActivity;

public class MainActivity extends AppCompatActivity {

   private static final String RECAPTCHA_SITE_KEY = "YOUR_RECAPTCHA_SITE_KEY";
   private static final String RECAPTCHA_HTML = "<html><head><script src='https://www.google.com/recaptcha/api.js'></script></head><body><form action='verify.php' 
method='post'><div class='g-recaptcha' data-sitekey='%s'></div><br><input type='submit' value='Submit'></form></body></html>";

   private WebView webView;

   @SuppressLint("SetJavaScriptEnabled")
   @Override
   protected void onCreate(Bundle savedInstanceState) {
      super.onCreate(savedInstanceState);
      setContentView(R.layout.activity_main);

      webView = findViewById(R.id.webView);
      webView.getSettings().setJavaScriptEnabled(true);
      webView.setWebViewClient(new WebViewClient() {
         @Override
         public boolean shouldOverrideUrlLoading(WebView view, WebResourceRequest request) {
            // Load URL within the WebView
            view.loadUrl(request.getUrl().toString());
            return true;
         }
      });

      // Load the reCAPTCHA HTML page
      String html = String.format(RECAPTCHA_HTML, RECAPTCHA_SITE_KEY);
      webView.loadData(html, "text/html", "UTF-8");
   }
}

//activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/
android"
   android:layout_width="match_parent"
   android:layout_height="match_parent">

   <WebView
      android:id="@+id/webView"
      android:layout_width="match_parent"
      android:layout_height="match_parent" />

</RelativeLayout>

Output

Using reCAPTCHA API with SafetyNet API (Without WebView)

This method removes the need for using a WebView by directly leveraging the SafetyNet API to verify the reCAPTCHA response. You invoke the verifyWithRecaptcha method from the SafetyNet API, providing your reCAPTCHA secret key and the user's response token as parameters. The API then asynchronously validates the response token. In the success callback, you can check whether or not the token result is empty. If it's not empty, it means that reCAPTCHA validation was successful, allowing you to proceed with your desired actions within the app.

Algorithm

  • Call the verifyWithRecaptcha method from the SafetyNet API.

  • Pass in your reCAPTCHA secret key and the user's response token.

  • The SafetyNet API asynchronously validates the response token.

  • In the success callback, check if the token result is empty or not.

  • If the token result is not empty, the reCAPTCHA validation is successful.

  • Perform the desired actions in your app based on the validation result.

Example

import android.os.Bundle;
import android.util.Log;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;

import com.google.android.gms.common.api.ApiException;
import com.google.android.gms.common.api.CommonStatusCodes;
import com.google.android.gms.safetynet.SafetyNet;
import com.google.android.gms.safetynet.SafetyNetApi;
import com.google.android.gms.tasks.OnFailureListener;
import com.google.android.gms.tasks.OnSuccessListener;
import com.google.android.gms.tasks.Task;

public class MainActivity extends AppCompatActivity {

   private static final String TAG = "MainActivity";
   private static final String SITE_KEY = "YOUR_SITE_KEY";

   @Override
   protected void onCreate(Bundle savedInstanceState) {
      super.onCreate(savedInstanceState);
      setContentView(R.layout.activity_main);

      verifyWithRecaptcha();
   }

   private void verifyWithRecaptcha() {
      SafetyNet.getClient(this).verifyWithRecaptcha(SITE_KEY)
            .addOnSuccessListener(this, new OnSuccessListener<SafetyNetApi.RecaptchaTokenResponse>() {
               @Override
               public void onSuccess(SafetyNetApi.RecaptchaTokenResponse response) {
                  if (response != null && response.getTokenResult() != null) {
                     String userResponseToken = response.getTokenResult();
                     Log.d(TAG, "onSuccess: userResponseToken=" + userResponseToken);
                     // Send the user response token to your server for verification
                     // Handle the server response accordingly
                     Toast.makeText(MainActivity.this, "reCAPTCHA success", Toast.LENGTH_SHORT).show();
                  }
               }
            })
            .addOnFailureListener(this, new OnFailureListener() {
               @Override
               public void onFailure(@NonNull Exception e) {
                  if (e instanceof ApiException) {
                     ApiException apiException = (ApiException) e;
                     int statusCode = apiException.getStatusCode();
                     Log.d(TAG, "onFailure: statusCode=" + statusCode);
                     // Handle error based on the status code
                     Toast.makeText(MainActivity.this, "reCAPTCHA failed", Toast.LENGTH_SHORT).show();
                  } else {
                     // Handle other exceptions
                     Toast.makeText(MainActivity.this, "Error occurred", Toast.LENGTH_SHORT).show();
                  }
               }
            });
   }
}

dependencies {
   // Other dependencies
   implementation 'com.google.android.gms:play-services-safetynet:17.0.0'
}

Output

Conclusion

In this tutorial, integrating Google reCAPTCHA into an Android application is a valuable step in enhancing security and preventing automated bot activities. Whether using the reCAPTCHA API with a WebView or directly utilizing the SafetyNet API, developers can effectively verify user authenticity, reduce spam and abuse, and ensure a safer and more reliable user experience. By implementing reCAPTCHA, Android apps can significantly strengthen their security measures and provide a trustworthy environment for genuine users.

Updated on: 27-Jul-2023

283 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements