python · January 16, 2023 0

How does Django REST framework integrate with JWT?

Table of Content

Django REST Framework is an excellent tool for building .It comes with Authentication Classes that help to build secure APIs.

Django REST Framework comes with various default Classes.BasicAuthentication, SessionAuthentication, and TokenAuthentication to name a few.

Token-based authentication is the most preferred method of implementing authentication in modern public relations.In this mechanism , the server generates a token along with all the HTTP requests to identify themselves.

The way tokenAuthentication is designed, it deletes the token every time the user logs out.This means making multi-device logins work is usually a pain.To get around this, one way is to choose to not delete the token on logout, but that is not recommended .

Enter JWT.


$ pip install -U djoser

If you are going to use JWT authentication, you will also need to install:

$ pip install -U djangorestframework_simplejwt

Finally if you are going to use third party based authentication e.g. facebook.

$ pip install -U social-auth-app-django





urlpatterns = [
    url(r'^auth/', include('djoser.urls')),

HTTP Basic Auth strategy is assumed by default.We strongly discourage and do not provide any explicit support for basic auth.You should customize your authentication backend.


We provide a standalone test app for you to start easily.It might be useful before integrating djoser .

$ git clone
$ cd djoser
$ pip install -e .

Go to the testproject directory, migrate the database .

$ cd testproject
$ ./ migrate
$ ./ runserver 8088

Register a new user:

$ curl -X POST --data 'username=djoser&password=alpine12'
{"email": "", "username": "djoser", "id":1}

We have just created a new user.

Let’s access user’’ details .

$ curl -LX GET
{"detail": "Authentication credentials were not provided."}

Let’S log in:

curl -X POST --data 'username=djoser&password=alpine12'
{"auth_token": "b704c9fc3655635646356ac2950269f352ea1139"}

We have just obtained an authorization token that we may use later.

Let’s access user’’ details again.

$ curl -LX GET
{"detail": "Authentication credentials were not provided."}

Access is still forbidden but let’s offer the token .

$ curl -LX GET -H 'Authorization: Token b704c9fc3655635646356ac2950269f352ea1139'
{"email": "", "username": "djoser", "id": 1}

Now let’S log out:

curl -X POST  --data 'b704c9fc3655635646356ac2950269f352ea1139' -H 'Authorization: Token b704c9fc3655635646356ac2950269f352ea1139'

And try access user profile again again.

$ curl -LX GET -H 'Authorization: Token b704c9fc3655635646356ac2950269f352ea1139'
{"detail": "Invalid token"}
%d bloggers like this: