Recaptcha v3 in Flutter app

How to implement reCAPTCHA v3 in Flutter app?

Google recaptcha v3 analyses the interactions of the users with the app and detects any abnormalities or suspicious use. It identifies whether the app is being accessed by a human or a bot. ReCaptcha v3 gives a score between 0 and 1 which indicates the risk based on the threshold you decide to set apart suspicious requests from genuine users. Today, we will cover how to setup google reCaptcha v3 for android / ios flutter apps.

If you are looking at specifically how to integrate in Flutter web project, I have written all about it here : https://feyashah.com/how-to-implement-google-recaptcha-v3

Step 1 : Create an ios / android app key

Go to your Google cloud project. Select reCaptcha Enterprise API and enable it for your project.

recaptcha V3

After enabling, go to the reCaptcha Dashboard. Create an ios and android app recaptcha key from this dashboard.

For the ios key, choose a correct display name, and select the platform type to be iOS App. In the bundle ids list, add your iOS Bundle ID. Your IOS Bundle ID can be found in PRODUCT_BUNDLE_IDENTIFIER field under ios / Runner.xcodeproj / project.pbxproj.

Similarly, create a key for android app as well. Add your android package for the key respectively.

Step 2 : Import reCaptcha Enterprise in your Flutter project

Install the recaptcha enterprise package. Here is the link to the package info : https://pub.dev/packages/recaptcha_enterprise_flutter

flutter pub add recaptcha_enterprise_flutter

Then, run

flutter pub get

In your main.dart file make the following changes :

import 'package:recaptcha_enterprise_flutter/recaptcha.dart';
import 'package:recaptcha_enterprise_flutter/recaptcha_client.dart';
import 'package:recaptcha_enterprise_flutter/recaptcha_enterprise.dart';
import 'package:recaptcha_enterprise_flutter/recaptcha_action.dart';

// Initialise the Google ReCaptcha Enterprise v3 client and use the sitekey based on your platform
String sitekey = "YOUR_ANDROID_APP_SITE_KEY";
if (Platform.isIOS) {
  sitekey = "YOUR_IOS_APP_SITE_KEY";
}
var result = await RecaptchaEnterprise.initClient(sitekey, timeout: 10000);

Step 3 : Get the ReCaptcha v3 Token in your Flutter project

 
import 'package:recaptcha_enterprise_flutter/recaptcha.dart';
import 'package:recaptcha_enterprise_flutter/recaptcha_client.dart';
import 'package:recaptcha_enterprise_flutter/recaptcha_enterprise.dart';
import 'package:recaptcha_enterprise_flutter/recaptcha_action.dart';

// Get the token using the appropriate sitekey based on the platform
RecaptchaClient? client = await Recaptcha.fetchClient(sitekey);
String token = await client?.execute(RecaptchaAction.LOGIN()) ?? "Client not initialized yet, click button InitClient";

Step 4 : Verify the reCAPTCHA v3 token on your backend

In my case, my flutter apps and my backend code which handles the authentication are in different google cloud projects. For the backend code to read and verify based on the site keys created in Step 1, you will need to give access to the backend service account to read the frontend project’s site keys.

Give the following permissions for the backend service account (For example, if your backend service is deployed on google cloud run, you need to give the following permissions to the default compute service account) :

  1. reCAPTCHA Enterprise Agent
  2. Service Account Token Creator
  3. Cloud reCAPTCHA Admin
  4. Cloud Run Invoker

In your backend code, add the following logic to verify the reCaptcha token.

   
const token = "TOKEN_RECEIVED_FROM_FRONTEND_PROJECT";
const projectId = "YOUR_FRONTEND_PROJECT_ID"; // this is to allow the backend project to read sitekeys from your frontend project
const apiUrl = `https://recaptchaenterprise.googleapis.com/v1/projects/${projectId}/assessments`;
  
const auth = new GoogleAuth({
  scopes: ["https://www.googleapis.com/auth/cloud-platform"],
});
  
try {
   const client = await auth.getClient();
    
   const requestBody = {
      event: {
         token: token,
         siteKey: "YOUR_SITEKEY_BASED_ON_THE_PLATFORM",
         expectedAction: "LOGIN",
      },
  };
    
const response = await axios.post(apiUrl, requestBody, {
    headers: {
       Authorization: `Bearer ${(await client.getAccessToken()).token}`,
       "Content-Type": "application/json",
   },
 });
  
const riskScore = response.data.riskAnalysis?.score || 0;
  
if (riskScore >= 0.5) {
   return res.json({ success: true, message: "Authentication passed" });
} else {
   return res.status(400).json({ success: false, message: "reCAPTCHA verification failed" });
 }
} catch (error) {
  console.error("Error verifying reCAPTCHA Enterprise:", error);
  return res.status(500).json({ success: false, message: "Internal Server Error" });
}

That’s it! You are all set to start using reCaptcha and make your site more secure. If you are also looking on how you can integrate it for your web app, do check out this article : https://feyashah.com/how-to-implement-google-recaptcha-v3

Hope this information was helpful. I would love to hear your feedback and issues you encountered while setting this up. Thank you!