reCAPTCHA v3
reCAPTCHA 已經進化到第三版了,個人覺得其驗證流程應該算更精簡了吧?
reCAPTCHA v3 部份內容是從 reCAPTCHA v2 繼承過來的,
在後端驗證還需要參考 reCAPTCHA v2 文件。
reCAPTCHA v3 主要特色是多了評分功能,
範圍從 1.0(看起來是真人) ~ 0.0(看起來像是機器人) 分,
後端程式可以去取得該評分,可以根據自身需求,
評分在多少分以上才被視為真人能通過程式。
範例如下
Model 為
ReCAPTCHA_V2_Response.cs
using Newtonsoft.Json;
using System;
namespace WebApplication1.Models
{
public class ReCAPTCHA_V2_Response
{
public bool success { set; get; }
public DateTime challenge_ts { set; get; }
public string hostname { set; get; }
[JsonProperty("error-codes")]
public string[] errorCodes { get; set; }
public string ErrorCodesToString()
{
string result = "";
foreach (string item in errorCodes)
{
result = result + " " + item;
}
return result;
}
}
}
ReCAPTCHA_V3_Response.cs
namespace WebApplication1.Models
{
public class ReCAPTCHA_V3_Response :ReCAPTCHA_V2_Response
{
public float score { set; get; }
public string action { set; get; }
}
}
Controller 為
HomeController.cs
using Newtonsoft.Json;
using System;
using System.IO;
using System.Net;
using System.Web.Mvc;
using WebApplication1.Models;
namespace WebApplication1.Controllers
{
public class HomeController : Controller
{
public ActionResult Index()
{
return View();
}
public ActionResult About()
{
ViewBag.Message = "Your application description page.";
return View();
}
public ActionResult Contact()
{
ViewBag.Message = "Your contact page.";
return View();
}
[HttpPost]
public ActionResult VerifyBot(string token)
{
try
{
string secret = "your_secret_key";
string g_recaptcha_response = token;
WebRequest WebRequest = WebRequest.Create("https://www.google.com/recaptcha/api/siteverify?secret=" + secret + "&response=" + g_recaptcha_response);
WebResponse WebResponse = WebRequest.GetResponse();
StreamReader sr = new StreamReader(WebResponse.GetResponseStream());
String apiResponse = sr.ReadToEnd();
sr.Close();
ReCAPTCHA_V3_Response ReCAPTCHA_V3_Response = JsonConvert.DeserializeObject<ReCAPTCHA_V3_Response>(apiResponse);
if (ReCAPTCHA_V3_Response.success == true && ReCAPTCHA_V3_Response.score >= 0.5)
{
return Content(apiResponse);
}
else
{
return Content(ReCAPTCHA_V3_Response.ErrorCodesToString());
}
}
catch (Exception ex)
{
//ViewBag.Success = ex.ToString();
return View();
}
}
}
}
View 為
Index.cshtml
@{ ViewBag.Title = "Home Page"; } <form id="myform" action="@Url.Action("")" method="post"> <input id="submit" type="submit" name="name" value="submit" /> </form> <script src='https://www.google.com/recaptcha/api.js?render=reCAPTCHA_site_key'></script> <script> grecaptcha.ready(function () { grecaptcha.execute('reCAPTCHA_site_key', { action: 'homepage' }) .then(function (token) { // Verify the token on the server. document.getElementById("myform").addEventListener("submit", function () { $.ajax({ type: 'POST', url: '@Url.Action("VerifyBot", "Home")', data: { token: token }, success: (res) => { console.log('result => ', res); } }); event.preventDefault(); }); }); }); </script>
參考資料: