Recaptcha in Angular JS

2019-04-28 14:46发布

I am implementing recaptcha in Angular JS, I am using "https://github.com/VividCortex/angular-recaptcha" url as reference. I have referred the Usage section and followed the instructions of code but still not able to get recaptcha in registration page.

Steps I have followed - 1. Generated a public key. 2. Added 3. Added div for recaptcha

  1. Added the anular-recaptcha.js in page - downloded form github code of above url.

Can anyone please let me know what I am missing in it? Can anyone can give me demo example link for recaptcha?

Thanks in advance.

5条回答
SAY GOODBYE
2楼-- · 2019-04-28 14:55

Sorry if you have already checked this...

They have a demo file here.

They also mention ..."Keep in mind that the captcha only works when used from a real domain and with a valid re-captcha key, so this file wont work if you just load it in your browser."

I followed their instructions and it worked okay for me.

查看更多
来,给爷笑一个
3楼-- · 2019-04-28 15:04

A good video demo to include google recaptcha in AngularJS application is given here AngularJS+ Google Recaptcha

It includes

  • Getting the public and private keys.
  • Using the public key in AngularJS
  • Using the private key in server code(Spring is used as server code here)

Hope this Demo helps.

查看更多
霸刀☆藐视天下
4楼-- · 2019-04-28 15:04

example that woked for me
register.cshtml:

<div vc-recaptcha key="'domain-key'" on-success="setResponse(response)"></div>

app.js:

var app = angular.module('myApp', ['ngRoute','vcRecaptcha']);

controller.js:

var ctrl = function ($rootScope, $scope, $location, $routeParams, registrationService) {

        $scope.reCaptchaResponse = "";
        $scope.setResponse = function (response) {
            $scope.reCaptchaResponse = response;
        };
        $scope.register = function () {
            var registration = {
                                ...
                reCaptchaResponse: $scope.reCaptchaResponse
            }
            $http.post(serviceBase + 'Register', registration).then(function (results) {                
                //return result
            });
        }
    }

Controller.cs:

[HttpPost]
    public JsonResult Register(UserDTO registration)
    {
        string responseFromServer = "";
        WebRequest request = WebRequest.Create("https://www.google.com/recaptcha/api/siteverify?secret=mysecret&response=" + registration.ReCaptchaResponse);
        request.Method = "GET";
        using (WebResponse response = request.GetResponse())
        {
            using (Stream stream = response.GetResponseStream())
            {
                StreamReader reader = new StreamReader(stream);
                responseFromServer = reader.ReadToEnd();
            }
        }

        if(responseFromServer != "")
        {
            bool isSuccess = false;          
            Dictionary<string, string> values = JsonConvert.DeserializeObject<Dictionary<string, string>>(responseFromServer);
            foreach (var item in values)
            {
                if (item.Key == "success" && item.Value == "True")
                {
                    isSuccess = true;
                    break;
                }                        
            }

            if(isSuccess)
            {
                //do something
            }
            else
            {
                //return reCaptcha error
            }

        }

        return Json(result);
    }
查看更多
何必那么认真
5楼-- · 2019-04-28 15:06

When working with angularjs and google recaptcha, the library you have used is the best option. But you have to take care of the following things for it to work.

  1. Include the library as explained into your angular project.
  2. Register your website and get the site keys.
  3. Include the widget, use your Site Key.
  4. Get the required g-captcha-response after the user solves the captcha.
  5. Make an ajax request to your server with the G-captcha-reposnse.
  6. On your backend verify the g-captcha-response using google's site verify API.

This link has a good explaination with a working example. Google recaptcha with angularJS

查看更多
ら.Afraid
6楼-- · 2019-04-28 15:14

Step1: Include captcha directive in form.html

<body ng-app="angularRecaptcha">
    <div class="col-md-6 col-md-offset-3 signupform" ng-controller="recapCtrl as recap">
      <form name="recap.signupForm" ng-submit="recap.signup()">
        .....
        ..
        <!--Recaptcha Widget--->
        <div vc-recaptcha key="recap.publicKey"></div>
        ...
        .....
    </form>
  </div>
<body>

Step2: Next is the App.js

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.

 angular.module(‘angularRecaptcha’,[‘vcRecaptcha’])
.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-response to our server
            }


/* MAKE AJAX REQUEST to our server with g-captcha-string */
                $http.post('http://sitename.com/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){

            })
        }
    }
}])

Step 3: Handle the POST request at api endpoint using SLIM PHP framework

<?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 answer.

$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 answer.

    /* return success scenario to client */
    echo json_encode(array(
    "error" => 0,
    "message" => "Successfully signed up!",
        "email" => $data['email'],
        "captchaResult" => $response["success"]
    ));
}

});
?>
查看更多
登录 后发表回答