The open blogging platform. Say no to algorithms and paywalls.

Django Rest Framework — JWT auth with Login and Register

Hello all. In this blog I am explaining how to perform JWT authentication (Login and Register )with Django REST Framework. Let's get started.

In my previous blog, I have explained what is JWT and how to initialize it with Django. To know about it, visit that blog.

Image uploaded for cover page. Ignore this Image.Image uploaded for cover page. Ignore this Image.

1. Creating a Django app and installing Django REST Framework

So now let's create a simple Django Project. I am creating a django project named jwtauthloginandregister. After creating it, I am just migrating to make the changes create our model in the database.

$ django-admin startproject jwtauthloginandregister
$ python3 manage.py migrate
$ python3 manage.py runserver

Now let's install django rest framework and django rest JWT.

$ pip3 install djangorestframework markdown django-filter djangorestframework_simplejwt

After installation, don't forget to add them to the Installed section.

jwtauthloginandregister/settings.py

# Application definition
INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'rest_framework', # Add this line
]

Also add the default authentication class as JWTAuthentication.

jwtauthloginandregister/settings.py

REST_FRAMEWORK = {
    'DEFAULT_AUTHENTICATION_CLASSES': [
        'rest_framework_simplejwt.authentication.JWTAuthentication',
     ],
}

JWT setup has been completed, but we cann't use it now because we didn't call it in the project level urls.py file. Let's do it.

jwtauthloginandregister/sestting.py

from django.conf.urls import url
from django.contrib import admin
from django.urls import path
from rest_framework_simplejwt import views as jwt_views

urlpatterns = [
    url(r'^admin/', admin.site.urls),
    path('api/token/', jwt_views.TokenObtainPairView.as_view(), name='token_obtain_pair'),
    path('api/token/refresh/', jwt_views.TokenRefreshView.as_view(), name='token_refresh'),
]

2. Create new a app to make authentication

Django JWT provides us a default login API. But it doesn't provide us a API for registration. We have to do it manually. To do it, I am creating a new app account in our project.

$ python3 manage.py startapp account

As usual, after creating an app, I am registering it to the Installed Apps section.

jwtauthloginandregister/settings.py

# Application definition
INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'rest_framework',
    'account', # Add this line
]

Now create a new file in the account app and just include the url in the project level urls.py file.

jwtauthloginandregister/urls.py

urlpatterns = [
    url(r'^admin/', admin.site.urls),
    path('api/token/', jwt_views.TokenObtainPairView.as_view(), name='token_obtain_pair'),
    path('api/token/refresh/', jwt_views.TokenRefreshView.as_view(),
name='token_refresh'),
    path('account/', include('account.urls')),
]

Now we have successfully set our app. Now let's start creating our Registration API.

3. Create authentication Views

To do that, I am creating two file api.py and serializer.py where api.py is the first point of contact from the urls.py file.

account/api.py

from rest_framework import generics, permissions, mixins
from rest_framework.response import Response
from .serializer import RegisterSerializer, UserSerializer
from django.contrib.auth.models import User

#Register API
class RegisterApi(generics.GenericAPIView):
    serializer_class = RegisterSerializer
    def post(self, request, *args,  **kwargs):
        serializer = self.get_serializer(data=request.data)
        serializer.is_valid(raise_exception=True)
        user = serializer.save()
        return Response({
            "user": UserSerializer(user,    context=self.get_serializer_context()).data,
            "message": "User Created Successfully.  Now perform Login to get your token",
        })

In the serializer.py, RegisterSerializer handles user registration. UserSerializer is used to retrive particular values of the users.

account/serializer.py

from rest_framework import  serializers
from rest_framework.permissions import IsAuthenticated
from django.db import models
from django.contrib.auth.models import User
from django.contrib.auth import authenticate
from django.contrib.auth.hashers import make_password

# Register serializer
class RegisterSerializer(serializers.ModelSerializer):
    class Meta:
        model = User
        fields = ('id','username','password','first_name', 'last_name')
        extra_kwargs = {
            'password':{'write_only': True},
        }

     def create(self, validated_data):
        user = User.objects.create_user(validated_data['username'],     password = validated_data['password']  ,first_name=validated_data['first_name'],  last_name=validated_data['last_name'])
        return user

# User serializer
class UserSerializer(serializers.ModelSerializer):
    class Meta:
        model = User
        fields = '__all__'

After creating these classes, just map the api endpoint to the urls.py of our newly created app.

account/urls.py

from django.conf.urls import url
from django.urls import path, include
from .api import RegisterApi

urlpatterns = [
      path('api/register', RegisterApi.as_view()),
]

Once created, open your postman and make a post request to http://localhost:8000/account/api/register

JWT auth RegistrationJWT auth Registration

Now after registration, Just login to get the JWT token. Now you can make request to the server with that token. To login, make a post request to http://localhost:8000/api/token/

JWT LoginJWT Login

JWT also handles login errors.

JWT Error handlingJWT Error handling

If you wanna know about the basics of JWT Authentication, Visit my previous blog.

In my next blog, I will be demonstrating how to use permissions and parse nested JSON.

Feel free to contact me for any queries. Email: sjlouji10@gmail.com. Linkedin: https://www.linkedin.com/in/sjlouji/

Complete Code can be found on my Github: https://github.com/sjlouji/Medium-Django-Rest-Framework-JWT-auth-login-register.git

Happy coding!




Continue Learning