如何在ASP.NET上实现recaptcha 2.0?

时间:2016-12-12 13:59:17

标签: asp.net recaptcha

我想在我的网页上实施recaptcha 2.0。我按照客户端的步骤从那里开始:

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

 <div class="g-recaptcha" data-sitekey="my_data-sitekey"></div>

但是,据我所知,这还不够。还有一些必须在服务器端完成。我应该怎么做?

3 个答案:

答案 0 :(得分:0)

您必须获取api才能使用此Google服务。

https://developers.google.com/recaptcha/docs/start

答案 1 :(得分:0)

以下是验证服务器端验证码的vb.net代码

Public Function ValidateCaptcha() As Boolean
        Dim valid As Boolean = False
        Dim Ressponse As String = Request("g-recaptcha-response")
        Dim strKey As String = ConfigurationManager.AppSettings("google.recaptcha.secretkey")
        Dim req As HttpWebRequest = Net.WebRequest.Create("https://www.google.com/recaptcha/api/siteverify?secret=" + strKey + "&response=" + Ressponse)
        Try
            Using wResponse As WebResponse = req.GetResponse()
                Using readStream As New StreamReader(wResponse.GetResponseStream())
                    Dim jsonResponse As String = readStream.ReadToEnd()
                    Dim js As New JavaScriptSerializer()
                    Dim data As MyObject = js.Deserialize(Of MyObject)(jsonResponse)
                    ' Deserialize Json
                    valid = Convert.ToBoolean(data.success)
                End Using
            End Using
            Return valid
        Catch ex As Exception
            Throw ex
        End Try
    End Function

这是MYObject类

Public Class MyObject
    Public Property success() As String
        Get
            Return m_success
        End Get
        Set(ByVal value As String)
            m_success = Value
        End Set
    End Property
    Private m_success As String
End Class

您需要从按钮点击事件中调用此ValidateCaptcha()函数,如下所示:

Protected Sub btnTrial_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnTrial.Click
If ValidateCaptcha() Then
   '''''Do your query here'''''
End If
End Sub

请参阅How to Validate Recaptcha V2 Server side以获取更多详情

答案 2 :(得分:0)

我做了一个简单易用的实现。

将以下课程添加到您的网络项目中。

1 2 30 
5 6 70
9 10 110

使用非常简单;

using System.Linq;
using System.Net.Http;
using Abp.Threading;
using Abp.Web.Models;
using Abp.Web.Mvc.Models;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Filters;
using Microsoft.AspNetCore.Mvc.ModelBinding;
using Microsoft.AspNetCore.Mvc.ViewFeatures;
using Newtonsoft.Json;

namespace WebDemo.Web.Attributes
{
    public class ValidateRecaptchaAttribute : ActionFilterAttribute
    {
        private readonly string _propertyName;
        private readonly string _secretKey;
        private readonly string _errorViewName;
        private readonly string _errorMessage;
        private const string GoogleRecaptchaUrl = "https://www.google.com/recaptcha/api/siteverify?secret={0}&response={1}";
        private const string SecretKey = "***YOUR PRIVATE KEY HERE***";

        public ValidateRecaptchaAttribute(string propertyName = "RepatchaValue", string secretKey = SecretKey, string errorViewName = "Error", string errorMessage = "Invalid captcha!")
        {
            _propertyName = propertyName;
            _secretKey = secretKey;
            _errorViewName = errorViewName;
            _errorMessage = errorMessage;
        }

        public override void OnActionExecuting(ActionExecutingContext context)
        {
            var model = context.ActionArguments.First().Value;
            var propertyInfo = model.GetType().GetProperty(_propertyName);
            if (propertyInfo != null)
            {
                var repatchaValue = propertyInfo.GetValue(model, null) as string;
                var captchaValidationResult = ValidateRecaptcha(repatchaValue, _secretKey);
                if (captchaValidationResult.Success)
                {
                    base.OnActionExecuting(context);
                    return;
                }
            }

            SetInvalidResult(context);
        }

        private void SetInvalidResult(ActionExecutingContext context)
        {
            var errorModel = new ErrorViewModel(new ErrorInfo(_errorMessage));
            var viewResult = new ViewResult
            {
                ViewName = _errorViewName,
                ViewData = new ViewDataDictionary(new EmptyModelMetadataProvider(), new ModelStateDictionary())
                {
                    Model = errorModel
                }
            };

            context.Result = viewResult;
        }

        private static RecaptchaResponse ValidateRecaptcha(string userEnteredCaptcha, string secretKey)
        {
            if (string.IsNullOrEmpty(userEnteredCaptcha))
            {
                return new RecaptchaResponse
                {
                    Success = false,
                    ErrorCodes = new[] { "missing-input-response" }
                };
            }

            using (var client = new HttpClient())
            {
                var result = AsyncHelper.RunSync<string>(() => client.GetStringAsync(string.Format((string)GoogleRecaptchaUrl, secretKey, userEnteredCaptcha)));
                var captchaResponse = JsonConvert.DeserializeObject<RecaptchaResponse>(result);
                return captchaResponse;
            }
        }

        public class RecaptchaResponse
        {
            [JsonProperty("success")]
            public bool Success { get; set; }

            [JsonProperty("challenge_ts")]
            public string ChallengeTs { get; set; }   // timestamp of the challenge load (ISO format yyyy-MM-dd'T'HH:mm:ssZZ)

            [JsonProperty("hostname")]
            public string Hostname { get; set; }      // the hostname of the site where the reCAPTCHA was solved

            [JsonProperty("error-codes")]
            public string[] ErrorCodes { get; set; }  // optional
        }
    }
}