{"id":104,"date":"2023-02-21T09:07:51","date_gmt":"2023-02-21T09:07:51","guid":{"rendered":"https:\/\/blessingcr.com\/?p=104"},"modified":"2023-02-21T09:07:52","modified_gmt":"2023-02-21T09:07:52","slug":"recaptcha-%e4%ba%ba%e6%9c%ba%e9%aa%8c%e8%af%81-%e6%8e%a5%e5%85%a5","status":"publish","type":"post","link":"https:\/\/blessingcr.com\/?p=104","title":{"rendered":"reCAPTCHA \u4eba\u673a\u9a8c\u8bc1 \u63a5\u5165"},"content":{"rendered":"\n<p class=\"wp-block-paragraph\">1. \u65b0\u5efagcloud \u9879\u76ee<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">2. \u542f\u7528recaptcha api\uff0c&nbsp;<a href=\"https:\/\/console.cloud.google.com\/security\/recaptcha?referrer=search&amp;orgonly=true&amp;project=metmake-backend-373703&amp;supportedpurview=organizationId\">https:\/\/console.cloud.google.com\/security\/recaptcha?referrer=search&amp;orgonly=true&amp;project=metmake-backend-373703&amp;supportedpurview=organizationId<\/a><\/p>\n\n\n\n<p class=\"wp-block-paragraph\">3. \u6dfb\u52a0\u670d\u52a1\u8d26\u53f7\uff0c \u5e76\u4e14\u6dfb\u52a0 captcha \u6743\u9650<\/p>\n\n\n\n<figure class=\"wp-block-image size-full\"><a href=\"https:\/\/blessingcr.com\/wp-content\/uploads\/2023\/02\/1676970424391.png\"><figure class=\"mdx-lazyload-container\" style=\"max-width:289px\"><div style=\"padding-top:59.861591695502%\"><\/div><div class=\"mdx-img-loading-sp mdui-valign\"><div><div class=\"mdui-spinner\"><\/div><\/div><\/div><img width=\"289\" height=\"173\" class=\"wp-image-106 lazyload\" title=\"reCAPTCHA \u4eba\u673a\u9a8c\u8bc1 \u63a5\u5165\" src=\"data:image\/gif;base64,R0lGODlhAQABAAAAACH5BAEKAAEALAAAAAABAAEAAAICTAEAOw==\" data-src=\"https:\/\/blessingcr.com\/wp-content\/uploads\/2023\/02\/1676970424391.png\" alt=\"https:\/\/blessingcr.com\/wp-content\/uploads\/2023\/02\/1676970424391.png\"><\/figure><\/a><\/figure>\n\n\n\n<p class=\"wp-block-paragraph\">4. \u751f\u6210sitekey\uff0c\u53ef\u4ee5\u5728\u4e0b\u9762\u7f51\u5740\u770b\u5230<a href=\"https:\/\/console.cloud.google.com\/security\/recaptcha?hl=zh-cn&amp;project=metmake-backend-373703\">https:\/\/console.cloud.google.com\/security\/recaptcha?hl=zh-cn&amp;project=metmake-backend-373703<\/a><\/p>\n\n\n\n<pre class=\"wp-block-preformatted\"><em>\/**<br><\/em><em> * Create reCAPTCHA Site key which binds a domain name to a unique key.<br><\/em><em> *<br><\/em><em> * <\/em><em>@param <\/em><em>projectID <\/em><em>: GCloud Project ID.<br><\/em><em> * <\/em><em>@param <\/em><em>domainName <\/em><em>: Specify the domain name in which the reCAPTCHA should be activated.<br><\/em><em> *\/<br><\/em>public String createSiteKey(String projectID, String domainName) throws IOException {<br>   \/\/ Initialize client that will be used to send requests. This client only needs to be created<br>   \/\/ once, and can be reused for multiple requests. After completing all of your requests, call<br>   \/\/ the `client.close()` method on the client to safely<br>   \/\/ clean up any remaining background resources.<br>   try (RecaptchaEnterpriseServiceClient client = RecaptchaEnterpriseServiceClient.<em>create<\/em>()) {<br><br>      \/\/ Set the type of reCAPTCHA to be displayed.<br>      \/\/ For different types, see: https:\/\/cloud.google.com\/recaptcha-enterprise\/docs\/keys<br>      Key scoreKey =<br>            Key.<em>newBuilder<\/em>()<br>                  .setDisplayName(\"want.net\")<br>                  .setWebSettings(<br>                        WebKeySettings.<em>newBuilder<\/em>()<br>                              .addAllowedDomains(domainName)<br>                              .setAllowAmpTraffic(false)<br>                              .setIntegrationType(IntegrationType.<em>SCORE<\/em>)<br>                              .build())<br>                  .build();<br><br>      CreateKeyRequest createKeyRequest =<br>            CreateKeyRequest.<em>newBuilder<\/em>()<br>                  .setParent(ProjectName.<em>of<\/em>(projectID).toString())<br>                  .setKey(scoreKey)<br>                  .build();<br><br>      \/\/ Get the name of the created reCAPTCHA site key.<br>      Key response = client.createKey(createKeyRequest);<br>      String keyName = response.getName();<br>      String recaptchaSiteKey = keyName.substring(keyName.lastIndexOf(\"\/\") + 1);<br>      System.<em>out<\/em>.println(\"reCAPTCHA Site key created successfully. Site Key: \" + recaptchaSiteKey);<br>      return recaptchaSiteKey;<br>   }<br>}<\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">5. \u524d\u7aef\u4f7f\u7528\u5bf9\u5e94\u7684sitekey \u62ff\u5230token<\/p>\n\n\n\n<pre class=\"wp-block-preformatted\">&lt;!DOCTYPE html&gt;<br>&lt;html lang=\"en\"&gt;<br><br>&lt;head&gt;<br>    &lt;script src=\"https:\/\/www.google.com\/recaptcha\/enterprise.js?render=6Le8H8kjAAAAANgPHcGsF40zXmorFg4_pm5MHYNu\"&gt;&lt;\/script&gt;<br>&lt;\/head&gt;<br>&lt;script  src=\"https:\/\/www.google.com\/recaptcha\/enterprise.js?render=6Le8H8kjAAAAANgPHcGsF40zXmorFg4_pm5MHYNu\"&gt;&lt;\/script&gt;<br>&lt;script&gt;<br>    grecaptcha.enterprise.ready(async () =&gt; {<br>        const token = await grecaptcha.enterprise.execute('6LcC9ssjAAAAACN9JhZlt_8AKxdjG6mtEqxbEnka', {action: 'homepage'});<br>        \/\/ IMPORTANT: The 'token' that results from execute is an encrypted response sent by<br>        \/\/ reCAPTCHA Enterprise to the end user's browser.<br>        \/\/ This token must be validated by creating an assessment.<br>        \/\/ See https:\/\/cloud.google.com\/recaptcha-enterprise\/docs\/create-assessment<br>        <em>console<\/em>.log(token);<br>    });<br>&lt;\/script&gt;<br><br>&lt;body&gt;<br><br>&lt;\/body&gt;<br><br>&lt;\/html&gt;<\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">6. \u540e\u7aef\u901a\u8fc7token\uff0c \u62ff\u5230\u5177\u4f53\u5206\u6570<\/p>\n\n\n\n<pre class=\"wp-block-preformatted\">public Boolean allow(String token, String action, Integer type) {<br>   \/\/ <em>TODO(developer): Replace these variables before running the sample.<br><\/em><em>   <\/em>String projectId = googleCloudCaptchaConfig.getProjectId();<br>   String recaptchaSiteKey = null;<br>   if (GoogleCloudCaptchaTypeEnum.<em>SCORE<\/em>.getType().equals(type)) {<br>      recaptchaSiteKey = googleCloudCaptchaConfig.getScoreKey();<br>   }<br>   if (GoogleCloudCaptchaTypeEnum.<em>CHALLENGE<\/em>.getType().equals(type)) {<br>      recaptchaSiteKey = googleCloudCaptchaConfig.getChallengeKey();<br>   }<br>   return createAssessment(projectId, recaptchaSiteKey, token, action) &gt;= googleCloudCaptchaConfig.getAllowScore();<br>}<br><br><em>\/**<br><\/em><em> * Create an assessment to analyze the risk of an UI action. Assessment approach is the same for<br><\/em><em> * both 'score' and 'checkbox' type recaptcha site keys.<br><\/em><em> *<br><\/em><em> * <\/em><em>@param <\/em><em>projectID        <\/em><em>: GCloud Project ID<br><\/em><em> * <\/em><em>@param <\/em><em>recaptchaSiteKey <\/em><em>: Site key obtained by registering a domain\/app to use recaptcha<br><\/em><em> *                         services. (score\/ checkbox type)<br><\/em><em> * <\/em><em>@param <\/em><em>token            <\/em><em>: The token obtained from the client on passing the recaptchaSiteKey.<br><\/em><em> * <\/em><em>@param <\/em><em>recaptchaAction  <\/em><em>: Action name corresponding to the token.<br><\/em><em> *\/<br><\/em>private float createAssessment(String projectID, String recaptchaSiteKey, String token, String recaptchaAction) {<br>   \/\/ Initialize client that will be used to send requests. This client only needs to be created<br>   \/\/ once, and can be reused for multiple requests. After completing all of your requests, call<br>   \/\/ the `client.close()` method on the client to safely<br>   \/\/ clean up any remaining background resources.<br>   try (RecaptchaEnterpriseServiceClient client = RecaptchaEnterpriseServiceClient.<em>create<\/em>()) {<br>      \/\/ Set the properties of the event to be tracked.<br>      Event event = Event.<em>newBuilder<\/em>().setSiteKey(recaptchaSiteKey).setToken(token).build();<br><br>      \/\/ Build the assessment request.<br>      CreateAssessmentRequest createAssessmentRequest =<br>            CreateAssessmentRequest.<em>newBuilder<\/em>()<br>                  .setParent(ProjectName.<em>of<\/em>(projectID).toString())<br>                  .setAssessment(Assessment.<em>newBuilder<\/em>().setEvent(event).build())<br>                  .build();<br><br>      Assessment response = client.createAssessment(createAssessmentRequest);<br><br>      \/\/ Check if the token is valid.<br>      if (!response.getTokenProperties().getValid()) {<br>         <em>log<\/em>.info(<br>               \"The CreateAssessment call failed because the token was: \"<br>                     + response.getTokenProperties().getInvalidReason().name());<br>         return -1f;<br>      }<br><br>      \/\/ Check if the expected action was executed.<br>      \/\/ (If the key is checkbox type and 'action' attribute wasn't set, skip this check.)<br>      if (!response.getTokenProperties().getAction().equals(recaptchaAction)) {<br>         <em>log<\/em>.info(<br>               \"The action attribute in reCAPTCHA tag is: \"<br>                     + response.getTokenProperties().getAction());<br>         <em>log<\/em>.info(<br>               \"The action attribute in the reCAPTCHA tag \"<br>                     + \"does not match the action (\"<br>                     + recaptchaAction<br>                     + \") you are expecting to score\");<br>         return -1f;<br>      }<br><br>      \/\/ Get the reason(s) and the risk score.<br>      \/\/ For more information on interpreting the assessment,<br>      \/\/ see: https:\/\/cloud.google.com\/recaptcha-enterprise\/docs\/interpret-assessment<br>      for (ClassificationReason reason : response.getRiskAnalysis().getReasonsList()) {<br>         <em>log<\/em>.info(\"reason:{}\", reason);<br>      }<br><br>      float recaptchaScore = response.getRiskAnalysis().getScore();<br>      <em>log<\/em>.info(\"The reCAPTCHA score is: \" + recaptchaScore);<br><br>      \/\/ Get the assessment name (id). Use this to annotate the assessment.<br>      String assessmentName = response.getName();<br>      <em>log<\/em>.info(\"Assessment name: \" + assessmentName.substring(assessmentName.lastIndexOf(\"\/\") + 1));<br>      return recaptchaScore;<br>   } catch (IOException e) {<br>      <em>log<\/em>.error(\"google cloud captcha err:{}\", e.getMessage());<br>      return -2;<br>   }<br>}<\/pre>\n","protected":false},"excerpt":{"rendered":"<p>1. \u65b0\u5efagcloud \u9879\u76ee 2. \u542f\u7528recaptcha api\uff0c&nbsp;https:\/\/console [&hellip;]<\/p>\n","protected":false},"author":1,"featured_media":0,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[22],"tags":[53,54],"class_list":["post-104","post","type-post","status-publish","format-standard","hentry","category-google-cloud","tag-recaptcha","tag-54"],"_links":{"self":[{"href":"https:\/\/blessingcr.com\/index.php?rest_route=\/wp\/v2\/posts\/104","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/blessingcr.com\/index.php?rest_route=\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/blessingcr.com\/index.php?rest_route=\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/blessingcr.com\/index.php?rest_route=\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/blessingcr.com\/index.php?rest_route=%2Fwp%2Fv2%2Fcomments&post=104"}],"version-history":[{"count":2,"href":"https:\/\/blessingcr.com\/index.php?rest_route=\/wp\/v2\/posts\/104\/revisions"}],"predecessor-version":[{"id":155,"href":"https:\/\/blessingcr.com\/index.php?rest_route=\/wp\/v2\/posts\/104\/revisions\/155"}],"wp:attachment":[{"href":"https:\/\/blessingcr.com\/index.php?rest_route=%2Fwp%2Fv2%2Fmedia&parent=104"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/blessingcr.com\/index.php?rest_route=%2Fwp%2Fv2%2Fcategories&post=104"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/blessingcr.com\/index.php?rest_route=%2Fwp%2Fv2%2Ftags&post=104"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}