📧 Email authentication in Django-Rest-Framework
Tags: django, webdev
Published: 2020-07-01 09:31:54

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*
{% youtube tAgDwEipToY %}

## 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-

```console
user@pc:~$ python3 -m venv env
```
Hold for a while...

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

```console
user@pc:~$ ls
env
user@pc:~$
```

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

`Activate it` by typing the following command.

```console
user@pc:~$ source ./env/bin/activate
user@pc:~$
```

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


```console
user@pc:~$ pip install django djangorestframework django-rest-auth django-allauth
```

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 - 

```console
user@pc:~$ django-admin startproject api
user@pc:~$
```

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.

```console
user@pc:~$ python manage.py runserver
```  

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.


```python
INSTALLED_APPS = [
    ...
    'django.contrib.sites',
    
    'allauth',
    'allauth.account',
    'allauth.socialaccount',
    
    'rest_auth',
    'rest_auth.registration',

    'rest_framework',
    'rest_framework.authtoken',

]
``` 


2. Add `SITE_ID` to settings.py file.

```python
SITE_ID = 1
```

3. Add `REST_FRAMEWORK` configurations to settings.py file.

```python
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'
    ]
}
```

4. Add these configurations to settings.py file for email authentication. Because by default Django uses authentication by `username` but we need `email auth`.

```python
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'
```

5. Change your `urls.py` code with this.

```python
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')),
]
```

6. Now we can migrate the database-

```console
user@pc:~$ python manage.py migrate
```

7. Let's create a Super User to access our Django Admin Panel.

```console
user@pc:~$ python manage.py createsuperuser
username: root
email: user@mail.com
password: 
Confirm Password: 
Successfully created superuser!
user@pc:~$
```  

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:
```json
{
    email: "user@gmail.com"
    password1: "MySecurePassword"
    password2: "MySecurePassword" 
}
```
response:
```json
{
    key: "xxxxxxxxxxxxxxxxxxxxxxxxxxxx"
}
```
![Alt Text](https://dev-to-uploads.s3.amazonaws.com/i/95mpo9l5e4jb4u6gm8cm.png)

2. Now, let's test `Login`.

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

Send the following `form data` along:

request:
```json
{
    email: "user@gmail.com"
    password: "MySecurePassword"
}
```
response:
```json
{
    key: "xxxxxxxxxxxxxxxxxxxxxxxxxxxx"
}
```
![Alt Text](https://dev-to-uploads.s3.amazonaws.com/i/8rd8mv0fv2m2w0813h2p.png)

**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](https://www.youtube.com/channel/UCCO4jIqmQVFDmVeeaAO5obA).

Happy Coding! 😃💻