Google reCAPTCHA

Laravel Auth: Google reCAPTCHA

Create Google reCAPTCHA v3

Go to Google reCAPTCHA to create your Google reCAPTCHA v3 service

After then you will get the SITE_KEY & SECRET_KEY

Google reCAPTCHA v3

Setting the key to your site

# .env
GOOGLE_RECAPTCHA_SITE_KEY=your_site_key
GOOGLE_RECAPTCHA_SECRET_KEY=your_secret_key

Import the Google reCAPTCHA v3 scripts to your site

You can follow the reCAPTCHA v3 Document to import your scripts to your sites

Create the /test/google-re-captcha route the test the page

Route::get('/test/google-re-captcha', function () {
    return view('test.googleRecaptcha');
});
<!-- resources/views/test/googleRecaptcha.blade.php -->
<html>
<head>
    <title>reCAPTCHA demo: Simple page</title>
    <script src="https://www.google.com/recaptcha/api.js"></script>
</head>
<body>
<form action="/register" method="POST" id="demo-form">
    <h1>Google Recaptcha</h1>

    <button class="g-recaptcha"
            type="submit"
            data-sitekey="{{env('GOOGLE_RECAPTCHA_SITE_KEY')}}"
            data-callback='onSubmit'
            data-action='submit'>Submit</button>
    <br/>
    {{ csrf_field() }}
</form>

<script>
    function onSubmit(token) {
        document.getElementById("demo-form").submit();
    }
</script>

</body>
</html>

Verify Google reCAPTCHA v3

Google will submit the g-recaptcha-response field value to your route by default

So we can create a new middleware to get the Google reCAPTCHA v3 verify result.

If the user didn’t pass the verification then you will respond error message to them from the middleware.

// app/Http/Middleware/ValidateGoogleRecaptchaMiddleware.php
class ValidateGoogleRecaptchaMiddleware
{
    public function handle($request, Closure $next)
    {
        $re_captcha_verify_response_json = file_get_contents(
            sprintf('https://www.google.com/recaptcha/api/siteverify?secret=%s&response=%s',
                env('GOOGLE_RECAPTCHA_SECRET_KEY'),
                $request->input('g-recaptcha-response')
            )
        );

        $ReCaptchaVerifyResponse = json_decode($re_captcha_verify_response_json);

        if (!$ReCaptchaVerifyResponse->success) {
            return response()->json(['error' => 'Invalid reCAPTCHA'], 400);
        }

        return $next($request);
    }
}

Setting this middleware to your app/Http/Kernel.php file and naming it as google-recaptcha

// app/Http/Kernel.php
protected $routeMiddleware = [
    // ...
    'google-recaptcha' => \App\Http\Middleware\ValidateGoogleRecaptchaMiddleware::class,
];

Google reCAPTCHA v3 Response

Verify Success

{
  "success": true,
  "challenge_ts": "2023-01-15T03:57:59Z",
  "hostname": "kj.com",
  "score": 0.9,
  "action": "submit"
}

Verify Failure

{
  "success": false,
  "error-codes": [
    "timeout-or-duplicate"
  ]
}

Protect your route by Google reCAPTCHA v3

You can set this google-recaptcha to the route that you want to protect.

// routes/api.php
Route::middleware(['google-recaptcha'])->group(function () {
    Route::post('/register', 'AuthController@register');
});

Reference