2
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

LaravelのデフォルトログインフォームにreCaptcha v3を付ける

Last updated at Posted at 2021-03-05

以下の組み合わせの情報が中々見つからなかったので。

  • Laravelのデフォルトのログインフォーム
  • ARCANEDEV/noCAPTCHA
  • reCaptcha v3
  • 2分間でトークンの有効期限が切れる問題の回避

使用しているのはLaravel8です。

ARCANEDEV/noCAPTCHAインストールなどは他のサイトにも情報があるため割愛し、ここではLaravelのファイルにどう記述するかだけを簡潔に記します。

.envにキーを設定

NOCAPTCHA_SECRET=your secret
NOCAPTCHA_SITEKEY=your site key

View

form内に{!! no_captcha()->input() !!}を入れ、ログインボタンにIDを付けておきます。

/resources/views/auth/login.blade.php
           <button type="button" class="btn btn-primary" id="login_button">
                ログイン
            </button>
        </div>
    </div>
    {!! no_captcha()->input() !!}
</form>

同じlogin.blade.php内に以下を記述。

/resources/views/auth/login.blade.php
{!! no_captcha()->script() !!}
{!! no_captcha()->getApiScript() !!}
<script>
$('#login_button').on('click', function (e) {
    e.preventDefault();grecaptcha.ready(function() {
        grecaptcha.execute('{{config('no-captcha.sitekey')}}', {action: 'submit'}).then(function (token) {
            $('#g-recaptcha-response').val(token)
            $('#login_form').submit()
        });
    });
});
</script>

Controller

validateLoginをオーバーライドしてCaptchaのバリデーションを入れます。

/app/Http/Controllers/Auth/LoginController.php
public function validateLogin(Request $request)
{
    $request->validate([
        $this->username() => 'required|string',
        'password' => 'required|string',
        'g-recaptcha-response' => ['required', new CaptchaRule]
    ], [
        'g-recaptcha-response.captcha'  => 'ロボットと判断されました',
    ]);
}

以上で動くはずです。何か記述漏れがありましたらご指摘ください。

2
2
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
2
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?