Tough on bots, easy on humans, this is Google’s “No CAPTCHA reCAPTCHA” and this tutorial will show you how to integrate it in your AngularJs projects.

Captchas are meant to protect your website from spam and abuse, Google has introduced this new service with quite a few innovative ways to prove you are a human and let you pass with ease while making it difficult for bots.

Overview

For the demo I’ll create a simple signup from with AngularJS which will include the reCaptcha widget. The user will have to solve the captcha to be able to submit the form. Solving the captcha will give us the “g-captcha-response” which we will verify at the back-end.

For client-side implementation I’ll be using angular-recaptcha library. This library will make it easier to use reCaptcha in our angular forms.

We will also need a web api to send “g-captcha-response” to our back-end, where we will have to verify it by making a post request to Google’s siteverify API. The API could be built using anything eg: nodejs, java, php.

For this demo I’m using php slim framework, I’ll add the sample code at the end.

Sections

Register your website to avail Google reCaptcha service

Client side implementation

Set up AngularJs project

Display reCaptcha Widget

Get g-captcha-response after user verifies

Make ajax request to server with g-captcha-response

Server side implementation

Verify user’s response with Google

DEMO DOWNLOAD

Note: The signup form is for demo purpose, we are not storing any information that you may enter, feel free to enter any random info.

Register your website to avail Google reCaptcha service

To register you website for reCaptcha visit https://www.google.com/recaptcha/, sign in with your Google account. Fill the register form with your domain details and hit register.

On successfully registering Google provides you with a site key and a secret key.

Site Key: You will use this on you client side code.

Secret Key: This will be used to communicate from your server to Google, make sure you keep it a secret.

Set up AngularJs project

You can skip to the next step if you are only looking for reCaptcha integration.

Below is our markup of a simple signup form with AngularJS. We have included the AngularJS library and bootstrap css files.

The angular app and controller is defined. We have a simple signup form setup with name, email and password fields. I’m using Angular’s “controller as” syntax in this example. You can know more about it here.

index.html

html >

head >

link href = "css/bootstrap.min.css" rel = "stylesheet" media = "screen" / >

link href = "css/bootstrap-theme.min.css" rel = "stylesheet" media = "screen" / >

/ head >

= "angularRecaptcha" > body ng-app

div class = "col-md-6 col-md-offset-3 signupform" ng-controller = "recapCtrl as recap" > ng-controller

form name = "recap.signupForm" ng-submit = "recap.signup()" > ng-submit

div class = "form-group" >

label > / label >

input type = "text" class = "form-control" ng-model = "recap.name" placeholder = "Enter Name" required> ng-modelplaceholderrequired>

/ div >

div class = "form-group" >

label > / label >

input type = "email" class = "form-control" ng-model = "recap.email" placeholder = "Enter email" required> ng-modelplaceholderrequired>

/ div >

div class = "form-group" >

label > / label >

input type = "password" class = "form-control" ng-model = "recap.password" placeholder = "Password" required> ng-modelplaceholderrequired>

/ div >

button type = "submit" class = "btn btn-default" > / button >

/ form >

/ div >



script src = "https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.3.15/angular.js" >< / script > >

script src = "js/app.js" >< / script > >

/ body >

/ html > NameEmail addressPasswordSubmit

Lets have a look at our app.js . Here I’ve defined the angular module and recapCtrl as our controller. The controller has a function as vm.signup() , that at the moment does nothing.

app.js

( function ( ) {

angular. module ( 'angularRecaptcha' , [ ] )



. controller ( 'recapCtrl' , [ function ( ) {

var vm = this ;



vm. signup = function ( ) {



}

} ] )

} ) ( )

Display reCaptcha Widget

We are using an angular library angular-recaptcha for our client side implementation.

The first thing we need to do is include reCaptcha library provided by Google into your project.

<script src=“https://www.google.com/recaptcha/api.js?onload=vcRecaptchaApiLoaded&render=explicit“ async defer></script>

Include the above line in your head tag. The onload callback is necessary to notify angular-recaptcha library that reCaptcha api is ready for usage.

Next download the angular-recaptcha library and include the js file in your project. You can install it using npm, bower or download it from the below link.

https://github.com/VividCortex/angular-recaptcha/blob/master/release/angular-recaptcha.min.js

Now inject the vcRecaptcha as dependency into you angular module.

angular.module(‘angularRecaptcha’,[‘vcRecaptcha’])

Adding the reCaptcha widget to the UI is easy, just add the directive as an attribute with your site key.

<div vc-recaptcha key=“‘—–YOUR SITE KEY ——‘” ></div>

Add the below to you code just after the password field in your HTML.

index.html

Then in your controller add the public key. Make sure you have injected vcRecaptcha as dependency in your module.

app.js

. controller ( 'recapCtrl' , [ function ( ) {

var vm = this ;



vm. publicKey = "----YOUR------SITE--------KEY---" ;



vm. signup = function ( ) {



}

...

...

......

Get g-captcha-response after user verifies

Now that we have the reCaptcha widget in our UI, the user can resolve the captcha. What we need now is the g-capthca-response string after the user resolves the captcha.

The angular-recaptcha library provides us with the vcRecaptchaService that has a getResponse() method, which provides us with g-captcha-response string after the user has successfully solved the captcha.

Have a look at the code below.

app.js

. controller ( 'recapCtrl' , [ 'vcRecaptchaService' , '$http' , function ( vcRecaptchaService , $http ) {

var vm = this ;

vm. publicKey = "----YOUR------SITE--------KEY---" ;



vm. signup = function ( ) {



/* vcRecaptchaService.getResponse() gives you the g-captcha-response */



if ( vcRecaptchaService. getResponse ( ) === "" ) { //if string is empty

alert ( "Please resolve the captcha and submit!" )

} else {

var post_data = { //prepare payload for request

'name' : vm. name ,

'email' : vm. email ,

'password' : vm. password ,

'g-recaptcha-response' : vcRecaptchaService. getResponse ( ) //send g-captcah-reponse to our server

}



}

}

} ] )

Here above we have first injected vcRecaptchaService into our controller, we have also injected $http service which we will need later on to make ajax request to the server.

In our vm.signup() function we are first checking if the value returned by vcRecaptchaService.getResponse() is an empty string, if yes that that means the user has not yet solved the captcha, so we alert them to do so.

In the else block we have also built up our request data, we are storing the user string that is returned by vcRecaptchaService.getResponse() in the key as g-recaptcha-response inside “post_data”

Make ajax request to server with g-captcha-response

Now we will send g-captcha-response string to our server via a post ajax request. I’ve created a signup API using php slim framework. Our Signup API takes email, name, password and g-captcha-response as parameters and then at the back-end it verifies the user response (i.e g-captcha-response) with the Google’s siteverify API and then returns relevant response to the client.

app.js

vm. signup = function ( ) {



/* vcRecaptchaService.getResponse() gives you the g-captcha-response */



if ( vcRecaptchaService. getResponse ( ) === "" ) { //if string is empty

alert ( "Please resolve the captcha and submit!" )

} else {

var post_data = { //prepare payload for request

'name' : vm. name ,

'email' : vm. email ,

'password' : vm. password ,

'g-recaptcha-response' : vcRecaptchaService. getResponse ( ) //send g-captcah-response to our server

}





/* MAKE AJAX REQUEST to our server with g-captcha-string */

$http. post ( 'http://code.ciphertrick.com/demo/phpapi/api/signup' , post_data ) . success ( function ( response ) {

if ( response. error === 0 ) {

alert ( "Successfully verified and signed up the user" ) ;

} else {

alert ( "User verification failed" ) ;

}

} )

. error ( function ( error ) {



} )

}

}

If the response from the ajax request is success and the error returned is 0, it means we have successfully verified the g-captcha-response string by Googles siteverify API.

See further below what we are doing when the signup API is hit.



Verify user’s response with Google

At our server when we receive the “g-captcha-response” string from our signup API, we have to verify the user’s response using the below API provided by google.

https://www.google.com/recaptcha/api/siteverify

This api takes three parameters for the POST request.

secret : ————YOUR SECRET KEY ———- response: g-captcha-response string received from the front-end. remoteip: —-THE USERS IP ADDRESS———–

For this applications implementation I’ve used php slim framework to build my signup Web API. I’ll only explain below, the code that runs when the API is invoked with required parameters. If you need to know more, or learn on how to build Web API’s using PHP Slim, we have an entire separate tutorial on that, click here.

api/routes/site.php (Signup API code)

<?php

$app -> post ( '/signup' , function ( ) use ( $app ) {

$req = $app -> request ( ) -> getBody ( ) ; //get request pramans

$data = json_decode ( $req , true ) ; //parse json string



//Should be some validations before you proceed

//Not in the scope of this tutorial.



$captcha = $data [ 'g-recaptcha-response' ] ; //Captcha response send by client



//Build post data to make request with fetch_file_contents

$postdata = http_build_query (

array (

'secret' => '-----YOUR SECRET KEY-------' , //secret KEy provided by google

'response' => $captcha , // g-captcha-response string sent from client

'remoteip' => $_SERVER [ 'REMOTE_ADDR' ]

)

) ;



//Build options for the post request

$opts = array ( 'http' =>

array (

'method' => 'POST' ,

'header' => 'Content-type: application/x-www-form-urlencoded' ,

'content' => $postdata

)

) ;



//Create a stream this is required to make post request with fetch_file_contents

$context = stream_context_create ( $opts ) ;



/* Send request to Googles siteVerify API */

$response = file_get_contents ( "https://www.google.com/recaptcha/api/siteverify" , false , $context ) ;

$response = json_decode ( $response , true ) ;





if ( $response [ "success" ] === false ) { //if user verification failed



/* return error scenario to client */

echo json_encode ( array (

"error" => 7 ,

"message" => "Robots Not allowed (Captcha verification failed)" ,

"captchaResult" => $response [ "success" ] ,

"captcahErrCodes" => $response [ "error-codes" ] //error codes sent buy google's siteVerify API

) ) ;

} else {



//Should be some Datatbase insertion to sign up the user

//before you return the success response

//Not in the scope of this tutorial.



/* return success scenario to client */

echo json_encode ( array (

"error" => 0 ,

"message" => "Successfully signed up!" ,

"email" => $data [ 'email' ] ,

"captchaResult" => $response [ "success" ]

) ) ;

}



} ) ;

?>

So when ever there is a request to our signup API the above block of code executes.

Explanation

First we get all the request params in the $req variable, then we use json_decode to parse the json string into $data .

Next we get the g-captcha-response string into $captcha variable.

We build $postdata then $opts and then create a stream from them using php’s stream_context_create($opts) function and put it into $context and then use this as options to make a post request using the file_get_contents(URL,false,$context) function to the below URL.

https://www.google.com/recaptcha/api/siteverify

This above API takes 3 parameters which I’ve already described above. This Google API verifies the user’s response string.

The response received from this API is as below.

{ "success": true|false, "error-codes": [...] // optional }

The response from the above API is stored in the $response variable.

If the verification is successful success key is returned as “true”, else its “false”. So depending on this we can take action.

If the verification is successful we return success scenario, else we return error and communicate it to the client by our signup API.

And then depending on the response returned to client we can take appropriate action in our UI. For the demo we are only showing an alert message.



Conclusion

Captcha’s are a must to protect your website from spam messages but some times they can shoo the actual users, Google’s new reCaptcha makes it much easier for humans to pass, at the same time making it more difficult for bots.

Also the reCaptcha widget looks cool as compared to older ones, plus the integration is very very easy. Hope this tutorial made it a lot more easier.

So go ahead and add this to your website.

Read more about it on Google’s official page.

Google’s official online security blog.