RECAPTCHAV3 in Laravel 9

Tram Ho

Google’s Recaptcha is a free and effective tool to combat Spam request – DDOS to your website.

Currently, google’s Recaptcha has version 3. Let’s add it to the project using Laravel, specifically version 9.

I add recaptcha to the pre-built project, if you don’t have a project, just search and build the Laravel project and come back here later!

After I have a project, I want to add Recaptchav3 to protect a specific page. Here, I take the login page as an example.

In the project, I run the following terminal to install the package: composer require josiasmontag/laravel-recaptchav3

then continue: php artisan vendor:publish –provider=”LunawebRecaptchaV3ProvidersRecaptchaV3ServiceProvider”

How to use Initialize Recaptcha Javascript Recaptcha v3 works best when it is loaded on every page to get the most context about interactions. Therefore, add to your header or footer template:

{!! RecaptchaV3::initJs() !!}

Next is the validation:

You can use rules in formRequest or use Validator library: here I use FormRequest:

public function rules() { return [ ’email’ => ‘bail|required|email’, ‘password’ => ‘bail|required|min:6|max:32’, ‘g-recaptcha-response’ => ‘ bail|required’ ]; }

Import FacadesRecaptchaV3 into the controller: use LunawebRecaptchaV3FacadesRecaptchaV3; // RecaptchaV3::verify($token, $action) $score = RecaptchaV3::verify($request->get(‘g-recaptcha-response’), ‘register’) if($score > 0.7) { // go } elseif($score > 0.3) { // require additional email verification } else { return abort(400, ‘You are most likely a bot’); }

You can also click the Recapcha icon with CSS: .grecaptcha-badge { visibility: hidden !important; }

Finally: You can choose several different Scores to test to see if the code is working as expected or not:

RecaptchaV3::shouldReceive(‘verify’) ->once() ->andReturn(1.0);

Thank you for reading up to here. The article has many shortcomings, I will try to improve it!

Source: https://github.com/josiasmontag/laravel-recaptchav3#readme

Share the news now

Source : Viblo