Adding Google reCAPTCHA v3 to Your Laravel App
reCAPTCHA is a great way to weed out bots from your site/app. Learn how to easily integrate it into your code using the reCAPTCHA API.
Join the DZone community and get the full member experience.
Join For FreeHi there. I want to share with you how I implemented Google’s reCAPTCHA v3 in my Laravel app.
Securing HTML forms from bots is an essential part of the security of any web app these days. One common and easy solution to this is implementing a captcha system. And Google’s reCAPTCHA v3 makes it quite easy to both implement as a developer and use as a user (v3 users do not have to select images to verify).
Let’s get started.
Check out BestOfLaravel.com - One place to learn all things Laravel
Registering a New Site
First off, we need to register our site in Google reCAPTCHA Admin and gain usage keys. When you add your site, also add localhost
in the list of domains, this will allow you to use the same key for development.
Once you submit these details, you should see two keys generated for your domain. One is the SITE KEY
which is used in the front-end and the other is the SECRET KEY
for usage in the server.
Front-End Setup
The front-end setup is pretty simple. Choose the page in which you want to implement reCAPTCHA, in my case I have a contact form on a page.
The below code shows a contact form with a hidden input named recaptcha
(it can be any name). Then at the end of that page add the reCAPTCHA’s JS library and once it’s ready we get a token and set it to the recaptcha
input.
Backend Setup
The above code checks if the current request is from a bot. We do this by sending a post request to Google's reCAPTCHA API with the SECRET KEY
and the TOKEN
from the front-end.
The resulting JSON has a property (success
) that is set to false when Google detects a request from a bot. Below is an example of what is returned.
Optimizing the Setup
Here’s a list of optimizations you could do to the above setup.
- Move the configuration keys to the
.env
file. - Move the verification logic to a custom validator.
Both of these are covered in the tutorial to which I've linked below.
Conclusion
There you have it. It’s pretty simple to add Google’s reCAPTCHA to your app. I would suggest you add this to all pages that can be visited by a bot. If you have any doubts, leave your questions below and I will try to help you.
Related Tutorials
Published at DZone with permission of Adi Sk. See the original article here.
Opinions expressed by DZone contributors are their own.
Comments