JWT stands for JSON Web Token. JWT is an open standard (RFC 7519) that defines a compact and self-contained way for securely transmitting information between parties as a JSON object. This information can be verified and trusted because it is digitally signed. JWTs can be signed using a secret (with the HMAC algorithm) or a public/private key pair using RSA or ECDSA. (official documentation)
JWT is an authentication strategy for securely transmitting information between parties as a JSON object. Basically, JWT has parts separated by dots. Which are header, payload, and signature.
Header: Identifies which algorithm is used to generate the signature. which means it is a JSON Object that contains meta-information about the token and how it is supposed to be signed.
Payload: JSON objects, The payload contain information such as userid and token expiration time
Signature: Securely validates the token. The signature only be generated and verified with a secret_key, thus making it secure against external tempering attacks
How does it work?
Once a user comes to your web application, he tries to enter your application with his username and password. After validating his credentials the server issues two JSON tokens, are Access token and a Refresh token. The front end of your application is saved the tokens and sends the access token in the authorization header of all the requests. When the request reaches the server it decodes the token and validates the token and finally identified the user as the logged-in user.
The access token is short-lived, which means they are only valid for a specific period of time. This is fully depending on the configuration that we have done. Once it’s expired if the user tries to access something shows the token is expired.
Installation & setup
Here we’re going to use the “djangorestframework-simplejwt” library recommended by Django developers.
pip install djangorestframework-simplejwt
settings.py
INSTALLED_APPS = [ ... 'rest_framework_simplejwt', ... ]
REST_FRAMEWORK = { 'DEFAULT_AUTHENTICATION_CLASSES': [ 'rest_framework_simplejwt.authentication.JWTAuthentication', ], }
urls.py
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'), . . . ]
You can also include a route for simple jwt TokenVerifyView if you wish to validate tokens.
Usage
To obtain a token you should send a post request to API. The API should contain two values username and password
If the login is successful the response should be like this:
{
Login success, jwt token generated
“access“:
“eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ0b2tlbl90eXBlIjoiYWNjZXNzIiwiZXhwIjoxNjcyOTE5OTA4LCJpYXQiOjE2NzI5MTkwMDgsImp0aSI6ImZjZGY5ODQ5NDMyMDRjMDI4ZWI0MDAxZjQzZTYxM2ZkIiwidXNlcl9pZCI6MzZ9.HgIGHCcRuEJNNmZ6kdpK9zs1PKEDaBNnkmZeze-s7g4”,
“refresh“: “eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ0b2tlbl90eXBlIjoicmVmcmVzaCIsImV4cCI6MTY3NDIxNTAwOCwiaWF0IjoxNjcyOTE5MDA4LCJqdGkiOiIyMDBlYTM3YzJlNDA0OWNhOTk4MmE5Y2NhOGJjOTBiYyIsInVzZXJfaWQiOjM2fQ.FmDRGr990_ZpkxVx5E83crmNdOWNR8zId125QocCgsY”
}
To access protected views you can add the access token in the header. The code is something like this
headers = {
header section to access protected views.
‘Authorization‘: ‘Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ0b2tlbl90eXBlIjoiYWNjZXNzIiwiZXhwIjoxODM0MjA4NjU3LCJpYXQiOjE2NzY1Mjg2NTcsImp0aSI6ImU3Mjg4ZTljNWQxYjRiNTFhNDUyODY2YWZkN2NhNGE5IiwidXNlcl9pZCI6Mjl9.j8XrXLz8V3mBCMz731cC5UFTF9YiOOsakRR83UtZ4mk’,
‘Content-Type‘: ‘application/json’
}
After 5 minutes access token will be expired, and if you want to access the protected views again you should use the refresh token as a payload to generate a new access token
payload={‘refresh’: ‘eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ0b2tlbl90eXBlIjoicmVmcmVzaCIsImV4cCI6MjI4NzMyNDQ0MzEzLCJpYXQiOjE2NzMyNDQzMTMsImp0aSI6IjUzMzlkMmUyNTVmMDRlMGFiYzY3NjQwNDllYzVjMTc0IiwidXNlcl9pZCI6NDB9.091p4_i_KKRknRZJ36LRSsfuchtQjn4_DxArLaCz8K4’}
requesting new access token
At the end
JWT is an open standard way that defines a self-contained way for securely transmitting data between parties as a JSON object. When the validation success we can create a pair of jwt tokens. It includes access and a refresh token. The access token used to access the protected views and refresh token helps to recreate the access token when it expired. To know more about read the simplejwtfulldoc