JWT Authentication using Django REST Framework

Deep into JWT tokens

Bismita Guha
AnitaB.org Open Source
2 min readJun 15, 2020

--

For authentication purposes, one of the common methods used is JSON Web Tokens or JWT. It’s a way for securely transmitting information between parties as a JSON object. Once the user is logged in, each subsequent request will include the JWT, allowing the user to access routes, services, and resources that are permitted with that token.

I have used the JWT authentication method in my GSoC project with AnitaB.org Open Source.

Parts of a JWT

  • Header
  • Payload
  • Signature

Header contains information about the algorithm of the JWT encrypt. In this the symmetric key algorithm HS256.

Payload is any data that needs to be included. This data is base64 encoded and a few fields like expiry and issuer should be added.

Signature is issued by the JWT backend, using the header base64 + payload base64 + SECRET_KEY . This needs to be sent in every request in the headers.

Implementation

I used the library djangorestframework_simplejwt for implementing the login for the OSP application.

The process becomes very simple with this library. First, we need to make a few changes. Add these lines in settings.py

urls.py

Now for any view which requires the user to be logged in, you need to attach Authorization header, which contains the token. The response received on login contains the access & refresh tokens. A refresh token is used to receive a new access token. Access tokens have small expiry time than refresh tokens.

In the frontend on login whenever the access token is received it needs to be stored in localStorage to be attached in headers with every request.

This was a summary of my work in the 2nd week of GSoC.

References

--

--