Google reCAPTCHA Integrating in Android Application 2022

Jyotishgher Astrology
By -
0

 

Google reCAPTCHA Integrating in Android Application 2022




we are sharing how to use Google reCAPTCHA Integrating into Android Application. An Android security purpose, you can add google re Captcha for registration form and query form in Android. Google reCAPTCHA is verified the user is not a robot its a real user.

While submitting some form or any other kind of information on a website, you might have noticed some captcha that you have to fill before submitting the details. That captcha may be of the form of an image having some numbers written on it and you just have to enter those numbers in the EditText provided to you. In Android, Another captcha can be an image and you have to identify user and robot.

In this Android blog, we will learn how to implement CAPTCHA using Google’s reCAPTCHA in our Android Application. So, let’s get started. Just follow these simple steps.


SafetyNet reCAPTCHA API

 

The SafetyNet service includes a reCAPTCHA API that you can use to protect your app from malicious traffic.

reCAPTCHA is a free service that uses an advanced risk analysis engine to protect your app from spam and other abusive actions. If the service suspects that the user interacting with your app might be a bot instead of a human, it serves a CAPTCHA that a human must solve before your app can continue executing.

Generate the reCAPTCHA Site Key and Secret Key

So, we have seen the flow of Google’s reCAPTCHA in the Android application. Our next step is to integrate this reCAPTCHA in our app. So, firstly we need to generate a Site Key and a Secret Key from the reCAPTCHA website. Follow the below steps:

  1. Visit the reCAPTCHA website.
  2. Enter the label to identify your key. You can enter any name here.
  3. After entering the label, select the reCAPTCHA type that you want to add to your app. I will be using reCAPTCHA v2 and after that reCAPTCHA Android.
  4. Enter the package name of your Android project.
  5. Finally, select the Accept the reCAPTCHA Terms and Conditions and Send alerts to owners.
  6. Click on Submit
  7. Hare, You Can see SITE_KEY, and SITE_SECRET_KEY.

Lest Integration in your Android App.

To register a key pair for use with the SafetyNet reCAPTCHA API, navigate to the reCAPTCHA Android signup site, then complete the following sequence of steps:

  1. In the form that appears, provide the following information:

    • Label: A unique label for your key. Typically, you use the name of your company or organization.
    • Package Names: Provide the package name of each app that uses this API key. In order for an app to use the API, the package name that you enter must be an exact match of the package name for that app. Enter each package name on its own line.
    • Send alerts to owners: Check this checkbox if you want to receive emails about the reCAPTCHA API.
  2. Check the Accept the reCAPTCHA Terms of Service checkbox, then click Register.

  3. In the Adding reCAPTCHA to your app section on the page that appears next, your public and private keys appear under Site key and Secret key, respectively. You use the site key when you send the verify request, and you use the secret key when you validate the user response token.

Google reCAPTCHA Integrating souce code

Step 1:  Add Dependency on our App build Gradle.

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



Step 2:-  Make a UI for Google reCAPTCHA.

<LinearLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:orientation="horizontal"
    android:layout_marginTop="20dp"
    android:padding="5dp">

    <TextView
        android:id="@+id/GoogleCaptchaText"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_weight="1"
        android:text="Google Captcha "
        android:textAppearance="@style/page_title" />

    <CheckBox
        android:id="@+id/GoogleCaptcha"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:buttonTint="@color/new_Blue" />

</LinearLayout>


TextView GoogleCaptchaText= (TextView) findViewById(R.id.GoogleCaptchaText);
CheckBox GoogleCaptcha= (CheckBox) findViewById(R.id.GoogleCaptcha);

Step 3: Add your java class Implication follow these codes.

add this method for your ReCaptcha generation in Android. You can add whare you want to show reCaptcha like on button click and Checkbox Click show.

String urlsiteverify = "https://www.google.com/recaptcha/api/siteverify";

private void validateCaptcha() {

// Showing reCAPTCHA dialog
SafetyNet.getClient(this).verifyWithRecaptcha("XXXXXXXXXXXXXXXXXXXXX")
.addOnSuccessListener(this, new OnSuccessListener<SafetyNetApi.RecaptchaTokenResponse>() {
@Override
public void onSuccess(SafetyNetApi.RecaptchaTokenResponse response) {
Log.d("Success", "onSuccess");
// Indicates communication with reCAPTCHA service was
// successful.
String userResponseToken = response.getTokenResult();

if (!response.getTokenResult().isEmpty()) {

// Received captcha token
// This token still needs to be validated on the server
// using the SECRET key
Log.e("VAL_STEP-", "VALIDATION STEP NEEDED" + userResponseToken);
verifyTokenOnServer(userResponseToken);

}else {
GoogleCaptcha.setChecked(false);
}
}
})
.addOnFailureListener(this, new OnFailureListener() {
@Override
public void onFailure(@NonNull Exception e) {
if (e instanceof ApiException) {
// An error occurred when communicating with the
// reCAPTCHA service. Refer to the status code to
// handle the error appropriately.
GoogleCaptcha.setChecked(false);
ApiException apiException = (ApiException) e;
Log.d("E", "Error message: " +
CommonStatusCodes.getStatusCodeString(apiException.getStatusCode()));
} else {
Log.d("Unknown", "Unknown type of error: " + e.getMessage());
}
}
});
}


/**
* Verifying the captcha token on the server
* Post param: recaptcha-response
* Server makes call to https://www.google.com/recaptcha/api/siteverify
* with SECRET Key and Captcha token
*/
private void verifyTokenOnServer(final String responseToken) {
Log.d("tokenNextPage", "-" + responseToken);


StringRequest strReq = new StringRequest(Request.Method.POST, urlsiteverify, new Response.Listener<String>() {

@Override
public void onResponse(String response) {
Log.d("VERIFYSUCCESS", "-" + response);
try {
json = new JSONObject(response);
// int success = json.getInt(TAG_SUCCESS);
boolean successb = json.getBoolean("success");
// String message = json.getString("message");
Log.d("VERIFYSUCCESS1", "-" + successb);
if (successb) {

GoogleCaptchaText.setText("You're not a Robot");
GoogleCaptcha.setChecked(true);
SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0);
SharedPreferences.Editor editor = settings.edit();

editor.putString(Empno, EMPNO);
editor.putString(Password, SECURITY_CODE);

startActivity(i);
overridePendingTransition(R.anim.slide_left_in, R.anim.slide_out_up);

} else {

GoogleCaptchaText.setText("High Security failed,Try Again!");
GoogleCaptcha.setChecked(false);


}
overridePendingTransition(
R.anim.activity_open_translate,
R.anim.activity_close_scale);
} catch (JSONException e) {
e.printStackTrace();
GoogleCaptcha.setChecked(false);
}

}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
GoogleCaptcha.setChecked(false);
Log.e("ERRORTOKEN", "Error: " + error.getMessage());
}
}) {
@Override
protected Map<String, String> getParams() {
Map<String, String> params = new HashMap<>();

params.put("secret", secret_key_google_captcha);
params.put("response", responseToken);
return params;
}
};
RequestQueue requestQueue = Volley.newRequestQueue(this);
strReq.setRetryPolicy(new DefaultRetryPolicy(
50000,
DefaultRetryPolicy.DEFAULT_MAX_RETRIES,
DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
requestQueue.add(strReq);


}

Post a Comment

0Comments

Post a Comment (0)