This boilerplate provides you with a basic Django project that implements JSON Web Tokens (JWT) authentication. It also has the reset password
functionality.
Clone this repo and cd into the project directory jwt_boilerplate
:
git clone https://github.com/itsmais/django-jwt-auth-boilerplate
cd django-jwt-auth-boilerplate/jwt_boilerplate
Start an environment called env
and activate it:
python -m venv venv
source venv/bin/activate # for linux
venv\Scripts\activate # for windows
Install Django within the virtual environment along with the 2 dependencies:
pip install django djangorestframework djangorestframework-simplejwt
Now, run migrations and create a superuser to be able to browse the admin dashboard and test this code:
python manage.py makemigrations authentication
python manage.py migrate
python manage.py createsuperuser
python manage.py runserver # optional: just to see how things are looking
Now, we need to give Django access to an email address to be able to send password reset notifications from it.
I chose to do this with a Gmail account, utilizing App Passwords. Here's a full guide on creating an App Password for a Gmail account. Once you have that, save it for the next step.
In settings.py
, change the email values depending on your provider. Of course, I am assuming that you would use a safe way to save and retrieve those passwords (like env variables) but this is out of scope for this guide.
EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend'
EMAIL_HOST = 'smtp.gmail.com' # change to your provider
EMAIL_PORT = 587
EMAIL_USE_TLS = True
EMAIL_HOST_USER = 'name@gmail.com' # change email address
EMAIL_HOST_PASSWORD = 'my app password' # email password
curl -X POST http://localhost:8000/api/register/ -H "Content-Type: application/json" -d '{
"username": "username",
"email": "user@example.com",
"password": "password"
}'
curl -X POST http://localhost:8000/api/token/ -H "Content-Type: application/json" -d '{
"username": "username",
"password": "password"
}'
To reset a a password, open http://localhost:8000/password_reset/ in the browser. Type in your email, and Django will send a reset link. This workflow uses Django's default views for this functionality.
Before you include this code in production, make sure that you follow the usual django checklist that you must follow before deployment, like taking care of the SECRET_KEY
in settings.py
, setting DEBUG
tofalse
, etc.