Django rest framework Part 2: Custom Authentication
Get the code here
Authentication is a way of validating someones identity via email, username, password, token,keys. Similar to default Django model, Django comes with default authentication as well but as it is stated in the Django documentation, you may need a custom authentication to suit your use case.
Tokens are mostly appropriate for client-side where state is stored after the user is authorized successfully. The token is stored in the local storage of the client and attached to the authorization header when making an API request which needs authentication.
Enough of talking lets get to work !!!
Ensure you have your environment activated, then run the following command to install PyJWT, you can skip the lock by specifying
pipenv install PyJWT — skip-lock
PyJWT is a Python library which allows you to encode and decode JSON Web Tokens (JWT)
Updating the Models
Inside app/authentication/models.py add the following at the import section.
from datetime import datetime, timedelta
from django.conf import settings
Under the User class add the following code.
This method generates and returns a string of the token generated
Inside app/authentication/serializers.py add the following code after the RegistrationSerializer class.
The above code creates a login serializer, that will be used to validate the required login credentials, and also gets the token string.
We need to receive login http request with email and password as the JSON data via our api. Write the following code in app/authentication/views.py
from .serializers import LoginSerializer
We’ll update app/authentication/urls.py with the login endpoint. Add the following code.
from .views import LoginAPIViewurlpatterns = [
path(‘login/’, LoginAPIView.as_view(), name=’user-registration’)
Finally! Lets run
$ python manage.py runserverSystem check identified no issues (0 silenced).
March 01, 2021–18:21:03
Django version 3.1.7, using settings ‘app.settings’
Starting development server at http://127.0.0.1:8000/
Quit the server with CONTROL-C
Navigate to http://127.0.0.1:8000/auth/login/ .Yeeah!! it works