How do I implement JWT authentication across multiple REST services in Django REST Framework?
I'm going to end up having multiple microservices for this project (calculation, customer, and others). The workflow is: the user logs in, gets the JWT, and then will be making multiple calls to the various services as long as the token has not expired.
I have created an authentication service in DRF using Simple JWT. The token call and refresh work great. I'm entirely new to DRF, so I don't know the best way to do this. How do I implement it so that the other services know that the token is valid? Architecturally, each microservice will be hosted in its own container in AWS. Is this something for which I could leverage AWS' API management?
Any help is greatly appreciated.
You can use the following approaches:
- Central Authentication Service:
By setting up central service for token generation using
djangorestframework-simplejwt
. You can add following as SIMPLE_JWT set up in settings.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'), ]
- JWT Validation in Microservices: Here, each microservice will valdiate tokens using the shared secret or public key:
REST_FRAMEWORK = { 'DEFAULT_AUTHENTICATION_CLASSES': ( 'rest_framework_simplejwt.authentication.JWTAuthentication', ), }
- Forwarding JWT for Inter Service Communcation: Pass JWT Token as Bearer token in Auth header while calling another service:
headers = {'Authorization': f'Bearer {user_token}'} response = requests.get('http://service/api/resource/', headers=headers)