Android SafetyNet ReCaptcha Integration and Verification

SafetyNet reCaptcha is used to protect your app, forms, website from spams and malicious traffic. reCAPTCHA provides a mechanism to safeguard from spam like bots or from misuse of your resources like traffic, bandwidth.

This post explains and provides working example of using reCaptcha in Android application. We will also see how to verify and validate reCaptcha response in our backend system.

Obtain reCAPTCHA key pair

The first step before we start integrating reCaptcha is to register the android app and generate key to authenticate reCaptcha API call. Obtain SafetyNet reCaptcha api key by signing up.

Create new reCaptcha site

  • Set Label to name your key
  • Set Package Name of Android App where reCaptcha validation will be used.
  • Accept Terms of Services

Android SafetyNet reCaptcha key settings

Once you submit the form you get Site key and secret key. Site key is used to send request to reCaptcha and Secret Key is used to validate the user response token.

Android Project

Create new Android project with Empty Activity. Add SafetyNet dependency in build.gradle file and sync gradle changes.

I have added Firebase functions in the gradle dependencies to calL Firebase Cloud backend function for validating user response token.

Android Resource

Update style.xml to support AppBarLayout and Toolbar.

Update AndroidManifest.xml to add style to the Activity.

Update activity layout to create Register form and validate user. activity_main.xml

Android Code Changes

  • Now open the activity file and update RECAPTCHA_KEY with your reCAPTCHA site key.
  • verifyReCaptchaAndRegister() calls SafetyNet api and displays Captcha dialog. On submission of the dialog a token is generated which needs to be sent to your backend server for validation.
  • verifyAndRegisterUser() calls Firebase Cloud Function and posts form data along with user token for validation.
  • The token is validated at the server. In this example I have used Firebase Cloud Functions to validate reCaptcha user token.

Validation of User Token in Firebase Cloud

In my past tutorial I have written about how to connect and use Firebase Cloud Functions. If you are new to Cloud Functions then the post is a starting point to understand how to use Google Firebase to create your own backend server.

Replace RECAPTCHA_SECRET with secret key obtained from reCAPTCHA.

Dependencies used in the above code are superagentfirebase-functions and firebase-admin


Leave a Reply