Google reCAPTCHA is one of the services provided by Google which is used to verify whether the user is a bot or not. The Google reCAPTCHA is seen in many websites and applications to verify the users. In this article, we will take a look at the implementation of Google reCAPTCHA in Android.
What we are going to build in this article?
We will be building a simple application in which we will be displaying a Google reCAPTCHA verify user button, after clicking that button we will display the Google reCAPTCHA to our user and verify them. A sample video is given below to get an idea about what we are going to do in this article. Note that we are going to implement this project using the Java language.
Working of Google reCAPTCHA
While using reCAPTCHA it makes several calls from your application to the Safety Net server and from the Safety Net server to your application. So you can get to know about these calls in more detail in the below diagram.
Steps in which we make API calls:
- For using reCAPTCHA in your application we have to generate a Site key and Secret Key which we have to add to our application. The site key is used in our Android application and the secret key is stored on the server.
- With the help of this site, key reCAPTCHA will be generated and it will verify if the user is a robot or not.
- After making verification by reCAPTCHA our application will communicate with our captcha server and it will return a response using your site key.
- Now our application will send a token to our server and our server will then send a token to the reCAPTCHA server with our Secret key. Then reCAPTCHA server will send a success response to our server and the server will send a success response to our application.
Step by Step Implementation
Step 1: Create a New Project
To create a new project in Android Studio please refer to How to Create/Start a New Project in Android Studio. Note that select Java as the programming language.
Step 2: Adding the dependency for volley and Safety Net
As we will be using the API provided by Google. So for using this API we will be using Volley for handling our HTTP requests and a safety net for connecting to Google reCAPTCHA.
implementation ‘com.android.volley:volley:1.1.1’
implementation ‘com.google.android.gms:play-services-safetynet:15.0.1’
After adding this dependency now sync your project and now we will move towards the creation of our API key which we will require for Google reCAPTCHA.
Step 3: Generating API key for using Google reCAPTCHA
For using Google reCAPTCHA we have to build two keys such as site key and site secret key which we have to use for authentication. For creating a new API key navigate to this Google developers site. And refer to the following diagram to generate the API keys.
After adding this data accept reCAPTCHA terms and then click on Submit option.
Step 4: Adding permissions for the Internet
As we are calling the API for Google reCAPTCHA so we have to add permissions for the Internet in our AndroidManifest.xml. Navigate to the app > AndroidManifest.xml and add the below code to it.
XML
< uses-permission android:name = "android.permission.INTERNET" /> |
Step 5: Working with the activity_main.xml file
Navigate to the app > res > layout > activity_main.xml and add the below code to that file. Below is the code for the activity_main.xml file.
XML
<? xml version = "1.0" encoding = "utf-8" ?> < RelativeLayout android:layout_width = "match_parent" android:layout_height = "match_parent" android:orientation = "vertical" tools:context = ".MainActivity" > <!--button for displaying our reCAPTCHA dialog box--> < Button android:id = "@+id/button" android:layout_width = "wrap_content" android:layout_height = "wrap_content" android:layout_centerInParent = "true" android:text = "Verify captcha" /> </ RelativeLayout > |
Step 6: Working with the MainActivity.java file
Go to the MainActivity.java file and refer to the following code. Below is the code for the MainActivity.java file. Comments are added inside the code to understand the code in more detail.
Java
import android.os.Bundle; import android.util.Log; import android.view.View; import android.widget.Button; import android.widget.Toast; import androidx.annotation.NonNull; import androidx.appcompat.app.AppCompatActivity; import com.android.volley.DefaultRetryPolicy; import com.android.volley.Request; import com.android.volley.RequestQueue; import com.android.volley.Response; import com.android.volley.VolleyError; import com.android.volley.toolbox.StringRequest; import com.android.volley.toolbox.Volley; 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 org.json.JSONObject; import java.util.HashMap; import java.util.Map; public class MainActivity extends AppCompatActivity { // variables for our button and // strings and request queue. Button btnverifyCaptcha; String SITE_KEY = "Enter Your Site Key Here" ; String SECRET_KEY = "Enter Your Secret Key Here" ; RequestQueue queue; @Override protected void onCreate(Bundle savedInstanceState) { super .onCreate(savedInstanceState); setContentView(R.layout.activity_main); queue = Volley.newRequestQueue(getApplicationContext()); btnverifyCaptcha = findViewById(R.id.button); btnverifyCaptcha.setOnClickListener( new View.OnClickListener() { @Override public void onClick(View v) { verifyGoogleReCAPTCHA(); } }); } private void verifyGoogleReCAPTCHA() { // below line is use for getting our safety // net client and verify with reCAPTCHA SafetyNet.getClient( this ).verifyWithRecaptcha(SITE_KEY) // after getting our client we have // to add on success listener. .addOnSuccessListener( this , new OnSuccessListener<SafetyNetApi.RecaptchaTokenResponse>() { @Override public void onSuccess(SafetyNetApi.RecaptchaTokenResponse response) { // in below line we are checking the response token. if (!response.getTokenResult().isEmpty()) { // if the response token is not empty then we // are calling our verification method. handleVerification(response.getTokenResult()); } } }) .addOnFailureListener( this , new OnFailureListener() { @Override public void onFailure( @NonNull Exception e) { // this method is called when we get any error. if (e instanceof ApiException) { ApiException apiException = (ApiException) e; // below line is use to display an error message which we get. Log.d( "TAG" , "Error message: " + CommonStatusCodes.getStatusCodeString(apiException.getStatusCode())); } else { // below line is use to display a toast message for any error. Toast.makeText(MainActivity. this , "Error found is : " + e, Toast.LENGTH_SHORT).show(); } } }); } protected void handleVerification( final String responseToken) { // inside handle verification method we are // verifying our user with response token. // url to sen our site key and secret key // to below url using POST method. // in this we are making a string request and // using a post method to pass the data. StringRequest request = new StringRequest(Request.Method.POST, url, new Response.Listener<String>() { @Override public void onResponse(String response) { // inside on response method we are checking if the // response is successful or not. try { JSONObject jsonObject = new JSONObject(response); if (jsonObject.getBoolean( "success" )) { // if the response is successful then we are // showing below toast message. Toast.makeText(MainActivity. this , "User verified with reCAPTCHA" , Toast.LENGTH_SHORT).show(); } else { // if the response if failure we are displaying // a below toast message. Toast.makeText(getApplicationContext(), String.valueOf(jsonObject.getString( "error-codes" )), Toast.LENGTH_LONG).show(); } } catch (Exception ex) { // if we get any exception then we are // displaying an error message in logcat. Log.d( "TAG" , "JSON exception: " + ex.getMessage()); } } }, new Response.ErrorListener() { @Override public void onErrorResponse(VolleyError error) { // inside error response we are displaying // a log message in our logcat. Log.d( "TAG" , "Error message: " + error.getMessage()); } }) { // below is the getParams method in which we will // be passing our response token and secret key to the above url. @Override protected Map<String, String> getParams() { // we are passing data using hashmap // key and value pair. Map<String, String> params = new HashMap<>(); params.put( "secret" , SECRET_KEY); params.put( "response" , responseToken); return params; } }; // below line of code is use to set retry // policy if the api fails in one try. request.setRetryPolicy( new DefaultRetryPolicy( // we are setting time for retry is 5 seconds. 50000 , // below line is to perform maximum retries. DefaultRetryPolicy.DEFAULT_MAX_RETRIES, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT)); // at last we are adding our request to queue. queue.add(request); } } |
After adding this code make sure to add the keys which we have generated inside your app. After adding the keys run your app and see the output of the app.