I want to verify the reCAPTCHA of my Android user. So I'm reading this documentation: https://developers.google.com/recaptcha/docs/verify:
For Android library users, you can call the SafetyNetApi.RecaptchaTokenResult.getTokenResult() method to get response token if the status returns successful.
In the manual of this function, the following description is written about getTokenResult
(https://developers.google.com/android/reference/com/google/android/gms/safetynet/SafetyNetApi.RecaptchaTokenResult.html#getTokenResult()):
Gets the reCAPTCHA user response token, which must be validated by calling the siteverify method described in Verify the user's response.
The manual of the siteverify
function describes the following (https://developers.google.com/android/reference/com/google/android/gms/safetynet/SafetyNetClient.html#verifyWithRecaptcha(java.lang.String)):
Provides user attestation with reCAPTCHA.
If reCAPTCHA is confident that this is a real user on a real device it will return a token with no challenge. Otherwise it will provide a visual/audio challenge to attest the humanness of the user before returning a token.
I want to use my backend server (Cloud Functions) to verify the reCAPTCHA. However, according to the Android documentation, all the above functions seem to be put client-side. Indeed, siteverify
should be called with the token got with getTokenResult
, and both seem to be part of the Android SecureNET ReCAPTCHA Android API...
However, I think that using Cloud Functions would be more secure! Can I use my backend however?
exports.verifyRecaptcha = functions.https.onRequest((request, response) => {
const user_response_token = request.query.user_response_token;
if(user_response_token == '') {
throw new functions.https.HttpsError('invalid-argument', 'The function must be called with an adequat user response token.');
}
const remote_url = 'https://www.google.com/recaptcha/api/siteverify';
const secret = null;
request.post({url: remote_url, form:{secret: secret, response: user_response_token}}, function(error, response, body) {
if(error) {
throw new functions.https.HttpsError('unknown', error);
}
if(!response.statusCode != 200) {
throw new functions.https.HttpsError('unknown', 'Something went wrong. Status code: ' + response.statusCode + '.');
}
if(!body.success) {
throw new functions.https.HttpsError('unknown', 'Unable to verify this captcha.');
}
return response;
});
});
You can take the token returned from getTokenResult()
, send it to your backend, and have your backend call the web API version of siteverify
:
https://www.google.com/recaptcha/api/siteverify