HomeCoding TutorialsHow to Implement Google SafetyNet ReCAPTCHA in Android Studio

How to Implement Google SafetyNet ReCAPTCHA in Android Studio

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.

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.

Add AndroiHire to your Google News feed.
Dhaval
Dhavalhttps://www.androidhire.com
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.

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Related Articles