如何在ASP.NET上实现Recaptcha 2.0? [英] How to implement recaptcha 2.0 on ASP.NET?

查看:102
本文介绍了如何在ASP.NET上实现Recaptcha 2.0?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在我的网页上实现 recaptcha 2.0 .我遵循了从那里开始的步骤:放在客户端:

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>

和:

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

推荐答案

我制作了一个简单易用的实现.

I made a simple and easy to use implementation.

将下面的类添加到您的Web项目中.

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

使用非常简单;

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

这篇关于如何在ASP.NET上实现Recaptcha 2.0?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆