ashrafZolkopli
Posted on June 14, 2021
In the previous post, I talked about how we could implement a simple trick to stop bot from continuing to submit a form in our web app. However like I told you, this might not be enough to keep all the bot from doing harm to our website. How to make it better? well another simple way is to implement a ReCaptcha. ReCaptcha is a relatively simple tool to identify if a web form in our site is being submitted by a human being or a robot. For this implementation ReCaptcha, a package called django-recaptcha.
Get Google ReCaptcha API keys
Before we can start using google ReCaptcha Api, first we need to register our application with google. I would propose to use Google ReCaptcha V3.
click on this link Google ReCaptcha Admin, and fill in the required information
click the submit button and copy your public and private api key
Installing django-recaptcha
You can start installing django-recaptcha with the following command in the terminal
pipenv install django-recaptcha
pipenv lock -r > requirements.txt
Registering django-recaptcha into your INSTALLED_APP
Open your settings.py and located the INSTALLED_APP list and register django-recaptcha like so
INSTALLED_APPS = [
#...
# Django-recaptcha
# https://github.com/praekelt/django-recaptcha
'captcha',
#...
]
django-recaptcha configuration
In the settings.py file, add the following setting config anywhere:
# Django-recaptcha
# https://github.com/praekelt/django-recaptcha
RECAPTCHA_PUBLIC_KEY = '<site_key>'
RECAPTCHA_PRIVATE_KEY = '<public_key>'
RECAPTCHA_REQUIRED_SCORE = 0.75
replace site_key and public_key from the api key you copied from google recaptcha.
if you are using python-decouple, the config would be
# Django-recaptcha
# https://github.com/praekelt/django-recaptcha
RECAPTCHA_PUBLIC_KEY = config('RECAPTCHA_PUBLIC_KEY')
RECAPTCHA_PRIVATE_KEY = config('RECAPTCHA_PRIVATE_KEY')
RECAPTCHA_REQUIRED_SCORE = config('RECAPTCHA_REQUIRED_SCORE', cast=float)
and in your .env file you should add the following
RECAPTCHA_PUBLIC_KEY = '<site_key>'
RECAPTCHA_PRIVATE_KEY = '<public_key>'
RECAPTCHA_REQUIRED_SCORE = <value between 0.00 to 1.00>
How to use django-recaptcha
If you want to use a ReCaptcha field inside your form, in your forms.py
from django import forms
from captcha.fields import ReCaptchaField
from captcha.widgets import ReCaptchaV3
class FormWithCaptcha(forms.Form):
captcha = ReCaptchaField(widget=ReCaptchaV3())
End
Now we are able to block user that fail the ReCaptcha test. This will stop most automated bot attack.
Posted on June 14, 2021
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.