DEV Community

Rajesh Joshi
Rajesh Joshi

Posted on • Edited on • Originally published at stackless.tech

๐Ÿ“ง Email authentication in Django-Rest-Framework

Whether a project is small, medium, or huge, it's most common necessity is authentication. And, E-mail auth is the widely used authentication method of all.

So, today I am helping you out to build e-mail authentication in Django Rest Framework (or, DRF).

NOTE: Here's the YouTube video of me, demonstrate the same

INDEX

  • Setting up the virtual environment
  • Creating the project
  • Configuring for authentication
  • Testing API

NOTE:: I'll recommend you, to use the bash shell, otherwise your commands will be a bit different.


Step 1. Setting up the virtual environment

For the python virtual environment, I am using venv. You can also use pipenv or virtualenv.

Open your terminal at the desired location and type the following command-

user@pc:~$ python3 -m venv env
Enter fullscreen mode Exit fullscreen mode

Hold for a while...

Now, type ls and it'll show our virtual environment env (it's the name of our environment).

user@pc:~$ ls
env
user@pc:~$
Enter fullscreen mode Exit fullscreen mode

Very Important step: Don't forget to activate the environment.

Activate it by typing the following command.

user@pc:~$ source ./env/bin/activate
user@pc:~$
Enter fullscreen mode Exit fullscreen mode

Now, we can install the required modules ie. django, djangorestframework, django-rest-auth and django-allauth

user@pc:~$ pip install django djangorestframework django-rest-auth django-allauth
Enter fullscreen mode Exit fullscreen mode

Now, our environment is all set up. And, we can now work on setting up the project itself.


Step 2. Creating the project

Now let's create our Django project by typing -

user@pc:~$ django-admin startproject api
user@pc:~$
Enter fullscreen mode Exit fullscreen mode

Here, api is the name of our project.

And yeah, our Django project is up and running. You can see the results in your browser by visiting http://127.0.0.1:8000 . But, before that don't forget to run the server using this command.

user@pc:~$ python manage.py runserver
Enter fullscreen mode Exit fullscreen mode

Till now 25% of our work is done.


Step 3. Configuring for authentication

By default, we have Django boilerplate, and we need to convert it to build API.

  1. Add rest_framework to INSTALLED_APPS inside your settings.py file.
INSTALLED_APPS = [
    ...
    'django.contrib.sites',

    'allauth',
    'allauth.account',
    'allauth.socialaccount',

    'rest_auth',
    'rest_auth.registration',

    'rest_framework',
    'rest_framework.authtoken',

]
Enter fullscreen mode Exit fullscreen mode
  1. Add SITE_ID to settings.py file.
SITE_ID = 1
Enter fullscreen mode Exit fullscreen mode
  1. Add REST_FRAMEWORK configurations to settings.py file.
REST_FRAMEWORK = {
    # Use Django's standard `django.contrib.auth` permissions,
    # or allow read-only access for unauthenticated users.
    'DEFAULT_PERMISSION_CLASSES': [
        'rest_framework.permissions.DjangoModelPermissionsOrAnonReadOnly'
    ]
}
Enter fullscreen mode Exit fullscreen mode
  1. Add these configurations to settings.py file for email authentication. Because by default Django uses authentication by username but we need email auth.
ACCOUNT_AUTHENTICATION_METHOD = "email"
ACCOUNT_EMAIL_REQUIRED = True
ACCOUNT_USERNAME_REQUIRED = False

AUTHENTICATION_BACKENDS = [
    # Needed to login by username in Django admin, regardless of `allauth`
    'django.contrib.auth.backends.ModelBackend',

    # `allauth` specific authentication methods, such as login by e-mail
    'allauth.account.auth_backends.AuthenticationBackend',
]

EMAIL_BACKEND = 'django.core.mail.backends.console.EmailBackend'
Enter fullscreen mode Exit fullscreen mode
  1. Change your urls.py code with this.
from django.contrib import admin
from django.urls import path, include

urlpatterns = [
    path('admin/', admin.site.urls),
    path('auth/', include('rest_auth.urls')),
    path('auth/registration/', include('rest_auth.registration.urls')),
]
Enter fullscreen mode Exit fullscreen mode
  1. Now we can migrate the database-
user@pc:~$ python manage.py migrate
Enter fullscreen mode Exit fullscreen mode
  1. Let's create a Super User to access our Django Admin Panel.
user@pc:~$ python manage.py createsuperuser
username: root
email: user@mail.com
password: 
Confirm Password: 
Successfully created superuser!
user@pc:~$
Enter fullscreen mode Exit fullscreen mode

now, run the server again and visit http://127.0.0.1:8000/admin/

Login with your admin credentials.


Step 4. Testing API

Open Postman or any other API testing application.

  1. First, let's test the Signup or Registration.

Make a POST request to 127.0.0.1:8000/auth/registration/

Send the following form data along:

request:

{
    email: "user@gmail.com"
    password1: "MySecurePassword"
    password2: "MySecurePassword" 
}
Enter fullscreen mode Exit fullscreen mode

response:

{
    key: "xxxxxxxxxxxxxxxxxxxxxxxxxxxx"
}
Enter fullscreen mode Exit fullscreen mode

Alt Text

  1. Now, let's test Login.

Make a POST request to 127.0.0.1:8000/auth/login/

Send the following form data along:

request:

{
    email: "user@gmail.com"
    password: "MySecurePassword"
}
Enter fullscreen mode Exit fullscreen mode

response:

{
    key: "xxxxxxxxxxxxxxxxxxxxxxxxxxxx"
}
Enter fullscreen mode Exit fullscreen mode

Alt Text

NOTE:* In the above responses, key is your web token, you can use to access the auth prevented routes.


Hurray! You just learned how to set up API end-points for Email authentication in Django Rest Framework.


I hope, you guys liked this quick tutorial. If so, then please don't forget to drop a Like โค๏ธ

And also, help me reach 1k Subscribers ๐Ÿคฉ, on my YouTube channel.

Happy Coding! ๐Ÿ˜ƒ๐Ÿ’ป

Top comments (3)

Collapse
 
eniayo profile image
einayo_a

When I used 127.0.0.1:8000/auth/registeration/ on POSTMAN it kept saying "{
"email": [
"This field is required."
],
"password1": [
"This field is required."
],
"password2": [
"This field is required."
]
}"

Collapse
 
rajeshj3 profile image
Rajesh Joshi

You have to pass these into the body or as raw JSON data.

Collapse
 
eniayo profile image
einayo_a

When I used 127.0.0.1:8000/auth/registeration/ on POSTMAN it kept saying "{
"email": [
"This field is required."
],
"password1": [
"This field is required."
],
"password2": [
"This field is required."
]
}" is there anyway I can solve this error it also shows error code 400 Bad request.