In Uncategorized

JSON Web Tokens (JWT) With Django and Implementation Example

A quick guide on how to install simple-jwt in your django project along with a quick demo on making an API call to restricted pages using your access token.

I will first show you how to get started and retrieve your access token, then we will use the fetch API to make a call to our views to access our protected view.

Reference Simple JWT documentation when needed.

Steps overview

  1. Installation and configuration
  2. Configure URLS
  3. Retrieve token
  4. Create API call in template
  5. Send token with all request to each view using fetch

Ensure you have Django REST Framework Installed

Before you get started with Simple JWT you will need to ensure that you have django REST framework installed ,

pip install djangorestframework

and add ‘rest_framework’ to “INSTALLED_APPS” within settings.py. 

INSTALLED_APPS = [

    …

    ‘rest_framework’,

]

1 – Installation and configuration

Pip install Simple JWT: pip install djangorestframework-simplejwt

Then configure the library in settings.py (rest_framework_simplejwt.authentication.JWTAuthentication) to the list of authentication classes:

(Explain what this does)

REST_FRAMEWORK = {

    …

    ‘DEFAULT_AUTHENTICATION_CLASSES’: (

        …

        ‘rest_framework_simplejwt.authentication.JWTAuthentication’,

    )

    …

}

2 – Configure URLS

Include routes for Simple JWT’s TokenObtainPairView and TokenRefreshView views:

from rest_framework_simplejwt.views import (

    TokenObtainPairView,

    TokenRefreshView,

)

urlpatterns = [

    …

    path(‘api/token/’, TokenObtainPairView.as_view(), name=’token_obtain_pair’),

    path(‘api/token/refresh/’, TokenRefreshView.as_view(), name=’token_refresh’),

    …

]

3 – Retrieving token

Before moving on to the next steps go ahead and let’s test the URLS by attempting to login as a user.

After you have your urls configured visit the path ‘api/token/’ and make sure that this returns a token. If everything was set up correctly you should see the prompt below asling you for your username and email.

When you give your credentials you should get back a “access” and “refresh” token like in the image below

http://127.0.0.1:8000/api/token/

Making API calls with our token on the fronted

Ok so we know how to do a little configuration and how to get a token but what about a real world example?

In this example we are going to create a simple fetch request to get a token from an html page and use that token to access a restricted page.

In our views.py we have 2 views. One for the page we will load and another for the restricted page we want to call. If we call this view without passing in a token we will get back a “Authentication credentials were not provided” response. 

Restricted view

URL’s that go with views 

urlpatterns = [
    ...
    path('api/token/', TokenObtainPairView.as_view(), name='token_obtain_pair'),
    path('api/token/refresh/', TokenRefreshView.as_view(), name='token_refresh'),
    ...
]

4 – Create API call in template

First we want to send a post request to the same url we used in step 4, this will imitate the access of a login form. We will use the fetch API to make this post request and consol out the response.

We should see this in the console when we load our page now. 

6 – Send token to get access to restricted view

No that we have our token we need to send it with every request back to our views.

You may choose to store this token in many different ways, some use localstorage others use cookies, but I’ll just keep mine in a variable called “accessToken”.

To send the data I created a function called sendData() and perform a simple get request. The only difference with this request is no I will add ‘Authorization’ to my headers and will pass in ‘Bearer’ as a string along with the accessToken variable. Make sure to leave a space between ‘Bearer’ and the accessToken. 

No the last thing I will do is trigger this function right after I get my access token and we will get whatever data that view returns.

var accessToken = null
var url = ‘/api/token/’
fetch(url, {
       method:’POST’,
            headers:{
               ‘Content-type’:’application/json’,
           },
        body:JSON.stringify({“username”: “dennisivy”,”password”: “password1qa”})
})
.then((response) => {
    return response.json();
  })
    .then((data) => {
     console.log(‘DATA:’, data);
     accessToken = data.accessToken
sendData()

    });
Contact Us

We're not around right now. But you can send us an email and we'll get back to you, asap.