How To Implement Google Recaptcha v3 on Your Django App

Muhammad Ihfazhillah
3 min readMay 22, 2019

--

https://nakedsecurity.sophos.com/2018/10/31/googles-stealthy-recaptcha-v3-detects-humans-no-questions-asked/

In this tutorial, I will show you how to implement google recaptcha v3 into your django app.

I also already create a simple django app, and what we will do here only to integrate the google recaptcha v3 in some views.

Let’s get started.

Clone App

Clone https://github.com/ihfazhillah/django-recaptchav3-example , then optionally create a virtualenv. Install the dependency.

FYI, the repo has 2 branches. master and final. Just start with master branch, and you can get the final result in the final branch.

Step 1: Register Google Recaptcha and Choose v3

Go to https://g.co/recaptcha/v3 , then create a new site.

Insert your Label, choose reCaptcha v3 in the recaptcha type.

Add localhost and 127.0.0.1 into domains field for local testing.

Accept the TOS. And then click submit.

You will see secret key and site key. The site key is what you need to implement google recaptcha v3 in the frontend. And secret key, keep it secret. This will be used for g-recaptcha's frontend response verification on your backend.

Step 2: Put Keys Into settings.py

Grab secret_key and site_key into settings.py like this:

and add site key into your index view

Step 3: Implement g-recaptcha on your frontend

open templates/index.html and add this javascript script:

  1. Use jquery to work with selector. It will make selection easier.
  2. Render the recaptcha v3 in your page
  3. when recaptcha ready, then
  4. when user click on submit button, execute grecaptcha to get the response token
  5. include the response token into form request and we will verify it on the backend

and add this hidden input in the form

now recaptcha activated !

Step 4: Implement g-recaptcha verification on your backend

open recaptcha_example/views.py and write down this on the contact view function:

  1. Get recaptcha response token from frontend.
  2. verify it
  3. if success true we can assumse that the user is not a robot, and process whole request
  4. if not, return error.
  5. Don’t forget to install requests package

If you curious, this is example of response from g-recaptcha verification

and I’m not a robot. Yay…

Conclusion

That’s all. We use google recaptcha v3, so there are no interruption to our visitor and we will get a score between 0.0 into 1.0 to indicate the visitor is a robot or human.

Thanks for reading, and hope you can implement it into your next project.

Originally published at https://blog.ihfazh.com on May 22, 2019.

--

--

Muhammad Ihfazhillah
Muhammad Ihfazhillah

Written by Muhammad Ihfazhillah

Teacher, freelancer software developer. Mainly code using python for scraping and web development.

Responses (2)