处理来自 AWS WAF 的验证码响应
本节提供了处理验证码响应的示例。
如果匹配的 Web 请求没有带有有效验证码时间戳的令牌,则带有 CAPTCHA 操作的 AWS WAF 规则将终止对该请求的评估。如果请求是 GET
文本/html 调用,则该 CAPTCHA 操作将向客户端提供带有验证码拼图的插页式广告。如果不集成验证码 JavaScript API,则会运行拼图;如果最终用户成功完成拼图,则会自动重新提交请求。
当您集成验证码 JavaScript API 并自定义验证码处理时,您需要检测终止的验证码响应,提供自定义验证码,然后如果最终用户成功完成拼图,则重新提交客户端的 Web 请求。
以下代码示例演示如何执行此操作。
注意
AWS WAF CAPTCHA 操作响应的状态码为 HTTP 405,我们用它来识别此代码中的 CAPTCHA 响应。如果您的受保护端点使用 HTTP 405 状态代码为同一调用传递任何其他类型的响应,本示例代码也会为这些响应显示验证码拼图。
<!DOCTYPE html> <html> <head> <script type="text/javascript" src="<Integration URL>/jsapi.js" defer></script> </head> <body> <div id="my-captcha-box"></div> <div id="my-output-box"></div> <script type="text/javascript"> async function loadData() { // Attempt to fetch a resource that's configured to trigger a CAPTCHA // action if the rule matches. The CAPTCHA response has status=HTTP 405. const result = await AwsWafIntegration.fetch("/protected-resource"); // If the action was CAPTCHA, render the CAPTCHA and return // NOTE: If the endpoint you're calling in the fetch call responds with HTTP 405 // as an expected response status code, then this check won't be able to tell the // difference between that and the CAPTCHA rule action response. if (result.status === 405) { const container = document.querySelector("#my-captcha-box"); AwsWafCaptcha.renderCaptcha(container, { apiKey: "...API key goes here...", onSuccess() { // Try loading again, now that there is a valid CAPTCHA token loadData(); }, }); return; } const container = document.querySelector("#my-output-box"); const response = await result.text(); container.innerHTML = response; } window.addEventListener("load", () => { loadData(); }); </script> </body> </html>