Google reCAPCHA là gì?
Google reCAPTCHA là một công cụ được Google phát hành, bằng việc từ chối gửi biểu mẫu, đăng ký tự động và hoạt động ở dạng robot theo cách an toàn, thông minh và hiệu quả nhất. Đồng thời Google reCAPTCHA còn giúp bảo vệ website của bạn bằng cách hạn chế spam tự động trên hệ thống của website.
Đăng ký Google Recaptcha v2
Truy cập website Google reCAPTCHA Admin Console. https://www.google.com/recaptcha/admin/. Sau đó click Admin Console nhé.
Để tạo api key cho website bạn tiến hành như sau nhé: click icon +Thêm tài khoản google reCaptcha.
Tiếp theo bạn điền thông tin Label, reCAPTCHA type, domain, Owners,Accept the reCAPTCHA Terms of Service và chọn Submit.
Phần domains bạn có thể nhập nhiều domain khác nhau.
Lưu thông tin site key và secret key. Sau khi submit , bạn sẽ thầy màn hình thông báo hiển thị site key và secret key như sau:
Tích hợp reCAPTCHA v2 vào website
Các bước thực hiện:
- Tạo Project ASP.NET
- Thêm key vào appsettings.json
- Thêm ReCaptchaService
- Khai báo Dependency Injection cho key settings và ReCaptchaService
- Thêm form ở View
- Xử lý token ở Action
Tạo Project ASP.NET 9, mở file appsettings.json, thêm đoạn config sau:
"GoogleReCaptchaV2": {
"SiteKey": "<your-site-key>",
"SecretKey": "<your-secret-key>"
}
ReCaptcha Service
Khai báo ReCaptchaResponsepublic class ReCaptchaResponse
{
public bool Success { get; set; }
}
Khai báo ReCaptchaService
public class ReCaptchaService
{
private readonly ReCaptchaSettings _settings;
public ReCaptchaService(IOptions<ReCaptchaSettings> settings)
{
_settings = settings.Value;
}
public async Task<bool> VerifyCaptchaAsync(string token)
{
using (var client = new HttpClient())
{
var response = await client.PostAsync($"https://www.google.com/recaptcha/api/siteverify?secret={_settings.SecretKey}&response={token}", null);
if (!response.IsSuccessStatusCode) return false;
var jsonResponse = await response.Content.ReadAsStringAsync();
var result = JsonConvert.DeserializeObject<ReCaptchaResponse>(jsonResponse);
return result?.Success ?? false;
}
}
}
Đăng ký Dependency Injection
services.Configure<ReCaptchaSettings>(Configuration.GetSection("GoogleReCaptchaV2"));
services.AddHttpClient<ReCaptchaService>();
Trên View bạn thêm g-recaptcha class
<style>
.captcha-error div div iframe {
border: 0.1em solid red;
}
</style>
<div id="captchaV" class="g-recaptcha" data-sitekey="@ViewBag.SiteKey"></div>
<script type="text/javascript">
function validationRecaptcha() {
var response = grecaptcha.getResponse();
var captchaContainer = document.getElementById("captchaV");
if (response.length === 0) {
captchaContainer.classList.add("captcha-error");
return false;
} else {
captchaContainer.classList.remove("captcha-error");
return true;
}
}
</script>
Khai báo Controller
public class RecaptchaV2Controller : Controller
{
private readonly ReCaptchaSettings _reCaptchaSettings;
public RecaptchaV2Controller(IOptions<ReCaptchaSettings> reCaptchaSettings)
{
_reCaptchaSettings = reCaptchaSettings.Value;
}
public IActionResult Login()
{
ViewBag.SiteKey = _reCaptchaSettings.SiteKey;
return View();
}
[HttpPost]
public async Task<IActionResult> Login(string name, string password, [FromServices] ReCaptchaService recaptchaService)
{
var gRecaptchaResponse = Request.Form["g-recaptcha-response"];
if (string.IsNullOrEmpty(gRecaptchaResponse) || !await recaptchaService.VerifyCaptchaAsync(gRecaptchaResponse))
{
ModelState.AddModelError(string.Empty, "Captcha is invalid, try again");
return View("Login");
}
return Content("Form submitted successfully!");
}
}
Nhận xét
Đăng nhận xét