LoginSignup
38
22

More than 5 years have passed since last update.

Google reCAPTCHA v3 を動かしてみる

Last updated at Posted at 2018-06-27

Google reCAPTCHA v3 を動かしてみる

現時点(2018年6月下旬)ではまだβバージョンらしいですが、reCAPTCHA v3をドキュメント通りに動かして見ました。

ドキュメント

v3とは

  • ユーザーのアクションなし
  • スコアを返す

と書いてあります。なるほど、シコシコと自動車の絵を探す必要はないのですね。

webページに導入する流れ

手順としては3つです。

  1. Load the JavaScript api with your sitekey
  2. Call grecaptcha.execute on an action or when the page loads
  3. Send the token to your backend with the request to verify(←GoogleのAPI)

0. Register(Keyの取得)

reCAPTCHA v3を導入するためにはまずは js 読み込みやトークン取得のためのKeyが必要になります。
上記ドキュメントにリンクがあってそこから辿っていけます。

recaptcha_v3_01.png

Key は2種類あります。

  • Site Key : HTMLに貼り付ける時に使う
  • Secret Key : Google にスコアを問い合わせる時に使う

どちらかというと、Secret Key の扱いに注意が必要ですね。

ちなみにこの画面、実際の画面で見ると右下に 「reCAPTCHA で保護されています」と出てきます。

reCAPTCHA_v3_02.png

つまり、reCAPTCHA の設定画面に reCAPTCHA が導入されている!

1. Frontend integration(HTMLに入れてトークン取得)

何かのアクションやwebページをロードしたタイミングでトークンを取得します。

ドキュメントには

  • js 読み込み
  • トークン取得

の方法が記載されています。

  <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) {
         ...
      });
  });
  </script>

Keyを取得するところでは実際の site_key が含まれた状態のサンプルが載ってるので便利です。
動作確認なので同じように入れます。

2. API Request/Response (スコア問い合わせ)

ドキュメント : Verifying the user's response

APIの問い合わせ方法もそれほど難しくありません。

{
  "success": true|false,      // whether this request was a valid reCAPTCHA token for your site
  "score": number             // the score for this request (0.0 - 1.0)
  "action": string            // the action name for this request (important to verify)
  "challenge_ts": timestamp,  // timestamp of the challenge load (ISO format yyyy-MM-dd'T'HH:mm:ssZZ)
  "hostname": string,         // the hostname of the site where the reCAPTCHA was solved
  "error-codes": [...]        // optional
}

action ってところは grecaptcha.execute 時に指定できます。
厳密な検証という意味では、このaction, challenge_ts, hostname あたりチェックしておくことも必要でしょう。

3. Interpreting the score(スコアに従った処理)

いわゆる「パズルを突破したらおk!」な方法ではないので、実際のプロダクトに入れていくことを考えるとここが一番大事になりますね。
ドキュメントには Use case / Recommendation として、bot判定への使い方みたいなのが書いてます。

動作確認用のwebページ

https://recaptcha-sample.appspot.com/ <- お金かかるので止めました。Elixir(Phoenix)なソースコードは https://github.com/ritou/elixir-recaptcha-example

取得したトークンを自分に投げて検証結果を表示するだけの人です。

よく使うブラウザで試すと高いスコアになりました。

recaptcha_v3_03.png

シークレットウィンドウだと低めになりました。

recaptcha_v3_04.png

botでは試してませんがいつかやる(やらなそう)

以上です。

38
22
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
38
22