How to implement recaptcha 2.0 on ASP.NET?

僤鯓⒐⒋嵵緔 提交于 2019-12-25 08:15:07

问题


I want to implement recaptcha 2.0 on my web page. I followed the steps from there by putting on client side:

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

and:

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

but, as far I understood, that's not enough. There is also something which must be done on server side. What and how should I do?


回答1:


You have to get an api in order to use this google service.

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




回答2:


Here is the vb.net code to validate captcha on server side

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

here is the class 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

And you need to call this ValidateCaptcha() function from your button click event as below:

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

Please refer How to Validate Recaptcha V2 Server side to get more details




回答3:


I made a simple and easy to use implementation.

Add the below class to your web project.

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
        }
    }
}

And usage is very simple;

[HttpGet]
[ValidateRecaptcha]
public ActionResult CreateProject(CreateModel model)
{
    //your main code that needs to be done after captcha validation.
}


来源:https://stackoverflow.com/questions/41102549/how-to-implement-recaptcha-2-0-on-asp-net

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!