How to Implement Google SafetyNet ReCAPTCHA in Android Studio
Coding Tutorials

How to Implement Google SafetyNet ReCAPTCHA in Android Studio

Dhaval
The SafetyNet service includes a reCAPTCHA API that you can use to protect your app from malicious traffic. In this tutorial we would see how we can implement Google SafetyNet RECAPTCHA in Android Studio.

ReCAPTCHA is a free service that protects your website from spam and abuse. ReCAPTCHA uses an advanced risk analysis engine and adaptive CAPTCHAs to keep automated software from engaging in abusive activities on your site. It does this while letting your valid users pass through with ease.

ReCaptcha

The reCAPTCHA Advantage

Advanced Security

State of the art spam & abuse protection for your website

Ease of Use

Low friction, effortless interaction for your users

Creation of Value

Apply the human bandwidth to benefit people everywhere

Prerequisites

  1. Android Studio installed on your computer.
  2. A Google Cloud project with the SafetyNet API enabled.
  3. Basic knowledge of Android development.

Steps to implement Google SafetyNet ReCAPTCHA in Android Studio

Step 1: Set Up Your Google Cloud Project

Restrict the API key to prevent unauthorized use (optional but recommended).

Go to the Google Cloud Console.

Create a new project or select an existing project.

Navigate to the API & Services section.

Enable the SafetyNet API for your project.

Create an API key:

Go to the Credentials tab.

Click on Create Credentials and select API Key.

Step 2: Add Dependencies to Your Project

Add the necessary dependencies to your build.gradle file.

dependencies {
    implementation 'com.google.android.gms:play-services-safetynet:18.0.1'
}

Sync your project to ensure the dependencies are downloaded.

Step 3: Request SafetyNet Attestation

Create a method to request the SafetyNet attestation in your MainActivity.

() { @Override public void onSuccess(SafetyNetApi.RecaptchaTokenResponse response) { // Get the response token String token = response.getTokenResult(); if (!token.isEmpty()) { // Handle the successful response handleSiteVerify(token); } else { Log.e(TAG, "Token is empty"); } } }) .addOnFailureListener(this, new OnFailureListener() { @Override public void onFailure(Exception e) { // Handle the error Log.e(TAG, "Error: " + e.getMessage()); Toast.makeText(MainActivity.this, "Error: " + e.getMessage(), Toast.LENGTH_SHORT).show(); } }); } private void handleSiteVerify(final String token) { OkHttpClient client = new OkHttpClient(); MediaType JSON = MediaType.get("application/json; charset=utf-8"); JSONObject jsonObject = new JSONObject(); try { jsonObject.put("token", token); } catch (JSONException e) { e.printStackTrace(); } RequestBody body = RequestBody.create(jsonObject.toString(), JSON); Request request = new Request.Builder() .url(SERVER_URL) .post(body) .build(); client.newCall(request).enqueue(new Callback() { @Override public void onFailure(Call call, IOException e) { Log.e(TAG, "Server request failed: " + e.getMessage()); } @Override public void onResponse(Call call, Response response) throws IOException { if (response.isSuccessful()) { Log.d(TAG, "Server response: " + response.body().string()); } else { Log.e(TAG, "Server request not successful"); } } }); } } " style="color:#D4D4D4;display:none" aria-label="Copy" class="code-block-pro-copy-button">
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.widget.Toast;
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;
import java.io.IOException;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;
import org.json.JSONException;
import org.json.JSONObject;

public class MainActivity extends AppCompatActivity {

    private static final String TAG = "SafetyNetDemo";
    private static final String SAFETYNET_API_KEY = "YOUR_API_KEY_HERE";
    private static final String SERVER_URL = "https://yourserver.com/verifyRecaptcha";

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

        // Call the SafetyNet API
        callSafetyNetAPI();
    }

    private void callSafetyNetAPI() {
        SafetyNet.getClient(this).verifyWithRecaptcha(SAFETYNET_API_KEY)
            .addOnSuccessListener(this, new OnSuccessListener<SafetyNetApi.RecaptchaTokenResponse>() {
                @Override
                public void onSuccess(SafetyNetApi.RecaptchaTokenResponse response) {
                    // Get the response token
                    String token = response.getTokenResult();
                    if (!token.isEmpty()) {
                        // Handle the successful response
                        handleSiteVerify(token);
                    } else {
                        Log.e(TAG, "Token is empty");
                    }
                }
            })
            .addOnFailureListener(this, new OnFailureListener() {
                @Override
                public void onFailure(Exception e) {
                    // Handle the error
                    Log.e(TAG, "Error: " + e.getMessage());
                    Toast.makeText(MainActivity.this, "Error: " + e.getMessage(), Toast.LENGTH_SHORT).show();
                }
            });
    }

    private void handleSiteVerify(final String token) {
        OkHttpClient client = new OkHttpClient();
        MediaType JSON = MediaType.get("application/json; charset=utf-8");
        JSONObject jsonObject = new JSONObject();
        try {
            jsonObject.put("token", token);
        } catch (JSONException e) {
            e.printStackTrace();
        }

        RequestBody body = RequestBody.create(jsonObject.toString(), JSON);
        Request request = new Request.Builder()
            .url(SERVER_URL)
            .post(body)
            .build();

        client.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                Log.e(TAG, "Server request failed: " + e.getMessage());
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                if (response.isSuccessful()) {
                    Log.d(TAG, "Server response: " + response.body().string());
                } else {
                    Log.e(TAG, "Server request not successful");
                }
            }
        });
    }
}

Step 4: Handle the Response on the Server

Your server needs to verify the reCAPTCHA token. Here is an example using Node.js and Express:

const express = require('express');
const axios = require('axios');
const bodyParser = require('body-parser');
const app = express();
const port = 3000;

app.use(bodyParser.json());

app.post('/verifyRecaptcha', async (req, res) => {
    const token = req.body.token;
    const secret = 'YOUR_SECRET_KEY';

    try {
        const response = await axios.post(`https://www.google.com/recaptcha/api/siteverify`, null, {
            params: {
                secret: secret,
                response: token
            }
        });

        if (response.data.success) {
            res.send({ success: true });
        } else {
            res.send({ success: false, 'error-codes': response.data['error-codes'] });
        }
    } catch (error) {
        res.send({ success: false, error: error.message });
    }
});

app.listen(port, () => {
    console.log(`Server running on port ${port}`);
});

Step 5: Test Your Implementation

  1. Run your Android app.
  2. Trigger the SafetyNet reCAPTCHA by performing the action that calls callSafetyNetAPI().
  3. Verify the token on your server.
  4. Check the logs or server responses to ensure everything is working as expected.

The Major Advantages of Using CAPTCHA

By distinguishing between humans and automated computer programs, reCAPTCHA offers safety and security in a number of ways.

1) Protecting Registration Forms in Websites

2) Preventing Spam Comments

3) Making Online Shopping More Secure

4) Protecting Email Accounts

CONCLUSION

This refined implementation ensures the SafetyNet reCAPTCHA token is correctly handled on the client side and sent to your server for verification. On the server side, the token is verified using Google's reCAPTCHA API. Make sure to replace YOUR_API_KEY_HERE and YOUR_SECRET_KEY with your actual API key and secret key from Google Cloud Console.

You no longer have to be concerned about automated signups, screen scrapers, or bot-generated spam.

Dhaval's profile picture

Dhaval

Dhaval is a consummate tech enthusiast with a penchant for software development and game creation. His technical prowess is reflected not only in his innovative projects but also in the insightful articles he pens. Beyond the world of technology, Dhaval immerses himself in the world of literature, indulging in novels that captivate his imagination during his leisure hours.

Related Posts

7 Top Samsung Galaxy Ring Alternatives for 2025

7 Top Samsung Galaxy Ring Alternatives for 2025

Tired of waiting for the Samsung Galaxy Ring to hit the market? You’re not alone. While the buzz around Samsung’s smart ring continues, a plethora of impressive alternatives is already available. These devices deliver advanced health tracking, stylish designs, and unique features that cater to various lifestyles. The current lineup of smart rings caters to […]

What Is Quiet Mode on Instagram and How to Activate It

What Is Quiet Mode on Instagram and How to Activate It

Ever wondered what Quiet Mode on Instagram is all about? This simple yet powerful Instagram feature helps you take a break from the constant buzz of notifications and focus on what truly matters. Whether you’re striving for better work-life balance, dedicating time to studying, or simply trying to disconnect from social media distractions, Quiet Mode […]

How to Make a Bed in Minecraft (Step-by-Step Guide)

How to Make a Bed in Minecraft (Step-by-Step Guide)

A bed in Minecraft is very important. It lets you skip the night and set your spawn point, so if you die, you will return to your bed instead of the original world spawn. This guide will show you how to gather materials, craft a bed, and set your spawn point. We’ll also show you how to customize your bed, build bunk […]

10 Best MMORPG Games For Android

10 Best MMORPG Games For Android

Not too long ago, MMORPG games and powerful gaming consoles were mostly exclusive to PCs. They required high-end graphics and systems to deliver their immersive gameplay. But times have changed. With the rise of gaming-oriented smartphones, you can now enjoy PC-like gaming experiences on your Android device. Thanks to these technological advancements and faster internet […]

Roblox: Fruit Battlegrounds codes (January 2025)

Roblox: Fruit Battlegrounds codes (January 2025)

Fruit Battlegrounds codes are all about getting more gems and help you to shoot up your rank in this One Piece anime-inspired game. This Fruit Battlegrounds was made by Popo developer. It is an action-packed game where players battle it out using unique fruit-based abilities. With constant updates, new fruits, and exciting challenges, it’s a fruity frenzy you won’t […]

Roblox: Ultimate Football Codes (January 2025)

Roblox: Ultimate Football Codes (January 2025)

Want to get some extra items for Ultimate Football in Roblox? You’ve come to the right place! Here’s the latest list of codes to help you score touchdowns and look stylish on the field. These codes offer free rewards such as coins and cosmetics to enhance your gameplay. What are Ultimate Football Codes? Ultimate Football […]

Roblox: Da Hood Codes (January 2025)

Roblox: Da Hood Codes (January 2025)

Are you a fan of Roblox games, in this article we will look at the Roblox Da Hood Codes for December 2024 that will help you unlock exclusive items, improve your gameplay and dominate the streets of Da Hood. You can feel that the game is inspired by the Grand Theft Auto series and there […]