google captcha with button validate-angularjs

时间:2016-04-13 09:03:45

标签: jquery angularjs validation

我在我的要求中使用Google重新验证代码。我想用按钮验证,如果我选择正确,那么只有按钮才会验证,否则它不是验证。我尝试了但是我失败了请先帮助我解决这个问题 这是我在线提供的Google验证码。

任何帮助都将不胜感激。

感谢。

这是我在线提供的google captcha脚本

 <script src='https://www.google.com/recaptcha/api.js'></script>


<form data-toggle="validator" role="form" name="myForm">Name: <input type="text" class="form-control" placeholder="Name" style="border: 1px solid #BBDEFB;"id="Name" ng-model="Name" required>Verification code: <div class="g-recaptcha" data-sitekey="6LcePAATAAAAAGPRWgx90814DTjgt5sXnNbV5WaW" required<button class="btn btn-default" style="background-color: #005baa; color: #fff;" ng-click="myForm.$valid && submit()">Submit</button></div></form>

这是我的按钮点击事件

$scope.submit = function () {
    //alert("hi");submit
    $scope.Name = "";
    var _EeqObj = new Object();
    _EeqObj.Name = $("#Name").val();
    _EeqObj.Meth = "WX";
    var httpreq = $http({
        method: 'POST',
        url: "Home",
        data: _EeqObj
    }).success(function (response) {
        if (response == "success") {
            alert("Thank You");
            $window.location.reload();
        }
        else {
            alert("not inserted");
            window.location.replace("#/");
        }
    });
}

2 个答案:

答案 0 :(得分:2)

你可以使用angular-recaptcha

https://github.com/VividCortex/angular-recaptcha

答案 1 :(得分:0)

仅在js客户端检查是不够的。 您还需要检查后端服务器端。客户端从谷歌验证码服务获取字符串响应。客户端将该字符串发送到您的服务器您的服务器将带有私钥的字符串发送到Google验证码服务,并根据答案决定。

更新: 这是与asp.net web api一起使用的代码部分

角度控制器

angular
    .module('yourApp', ['vcRecaptcha'])
    .controller('YourController', YourController);

function YourController($scope, vcRecaptchaService) {

    var recaptcha = {
        key: "your recaptcha public key",
        widgetId: null,
        response: null,
        setWidget: function(widgetId) { recaptcha.widgetId = widgetId; },
        setResponse: function(response) { recaptcha.response = response; },
        cbExpiration: function() { recaptcha.response = null; },
        reset: function () {
            recaptcha.response = null;
            vcRecaptchaService.reload(recaptcha.widgetId);
        }
    };

    $scope.recaptcha = recaptcha;

    $scope.reset = function() {
        $scope.info = undefined;
        recaptcha.reset();
    };


    $scope.sendData = function(form, recaptchaResponse) {
        if (form.$invalid) return;
        $http.post('/api/endpoint', { data: ..., recaptchaResponse: recaptchaResponse})
            .then(...

角度视图

<form name="yourForm" novalidate ng-submit="sendData(yourForm, recaptcha.response)>
...
    <input type="hidden" name="recaptchaResponse" ng-model="recaptcha.response" required/>
    <div class="recaptcha-container">
        <div vc-recaptcha theme="'light'" key="recaptcha.key"
             on-create="recaptcha.setWidgetId(widgetId)"
             on-success="recaptcha.setResponse(response)"
             on-expire="recaptcha.cbExpiration()"></div>
    </div>
    <span class="recaptcha-error-info" ng-show="yourForm.$submitted && (yourForm.recaptchaResponse.$invalid || yourForm.$error.recaptcha.length)">
        Pass the check, please
    </span>
...

asp.net web api controller

[RoutePrefix("api")]
public class YourApiController : ApiController
{
    [HttpPost]
    [Route("endpoint")]
    public async Task<IHttpActionResult> Post([FromBody] YourVm model)
    {
        if (!ModelState.IsValid) return BadRequest(ModelState);

        var remoteIp = Request.GetOwinContext().Request.RemoteIpAddress;
        var recaptchaVerifyResponse = await VerifyAsync(model.RecaptchaResponse, remoteIp);

        if (recaptchaVerifyResponse == null || !recaptchaVerifyResponse.Success) return BadRequest("recaptcha error");

        ...
    }


    // may be exrtracted into service
    private async Task<RecaptchaVerifyResponse> VerifyAsync(string response, string remoteip)
    {
        const string RecaptchaVerifyUrl = "https://www.google.com/recaptcha/api/siteverify";

        string responseString;
        using (var client = new HttpClient())
        {
            var values = new Dictionary<string, string>
            {
                {"secret", "your recaptcha private key"},
                {"response", response},
                {"remoteip", remoteip},
            };

            var content = new FormUrlEncodedContent(values);
            var postResponse = await client.PostAsync(RecaptchaVerifyUrl, content);
            responseString = await postResponse.Content.ReadAsStringAsync();
        }

        if (string.IsNullOrWhiteSpace(responseString)) return null;

        RecaptchaVerifyResponse result;
        try
        {
            result = JsonConvert.DeserializeObject<RecaptchaVerifyResponse>(responseString);
        }
        catch (JsonException)
        {
            return null;
        }

        return result;
    }
}

public class RecaptchaVerifyResponse
{
    [JsonProperty("success")]
    private bool? _success = null;

    public bool Success
    {
        get { return _success == true; }
    }

    [JsonProperty("error-codes")]
    private string[] _errorCodes = null;

    public string[] ErrorCodes
    {
        get { return _errorCodes ?? new string[0]; }
    } 
}
相关问题