Adding Google reCAPTCHA v3 to your Laravel App
Adi · 31/Mar/19
Hi 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 (with v3 users do not have to select images to verify).
Let’s get started.
Need a Laravel Developer for your Project?
You can find my contacts here
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.
Frontend Setup
Front end setup is pretty simple. Choose the page you want to implement reCAPTCHA, in my case I have a contact form on a page.
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 reCAPTCHA API with the SECRET KEY
and the TOKEN
from the frontend.
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 which are covered in the tutorial 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 do leave them below, I will try to help you.
That’s all for now. More about me at SimplestWeb.in
Check out my side project - LaravelCollections.com
Related tutorials