Introduction
rest_framework_jwt.views provides us refresh_jwt_token to get new token before the token expired.
What do we have to so if we want to store refresh token in the HttpOnly token? This topic is the note for Refreshing JWT in the HttpOnly cookie
1. Add an Endpoint for returning the Refresh JWT in the response body
- Edit the urls.py
...
from rest_framework_jwt.views import refresh_jwt_token
urlpatterns = [
...,
path('api/refresh-token-auth/', refresh_jwt_token, name='refresh-token-auth'),
]
2. Add an Endpoint to add Refresh JWT in the HttpOnly cookie
- Edit views.py
...
class RefreshTokenView(generics.GenericAPIView):
authentication_classes = []
permission_classes = (permissions.AllowAny,)
def get(self, request):
token = request.COOKIES.get('token')
data = {'token':token}
scheme = request.is_secure() and "https" or "http"
url = scheme + "://" + request.get_host() + '/api/refresh-token-auth/'
res = requests.post(url, data = data)
if res.status_code == status.HTTP_200_OK:
print(json.loads(res.text)["token"])
response = Response(status=status.HTTP_200_OK)
response.set_cookie('token', json.loads(res.text)["token"], httponly=True)
return response
else:
return Response(status=res.status_code)
renew_token= RefreshTokenView.as_view()
- Edit the urls.py
...
from .views import renew_token
urlpatterns = [
...,
path('api/renew-token/', renew_token, name='renew-token')
]
That's it!
Articles
There are some of my articles. Feel free to check if you like!
- My blog-posts for software developing: https://medium.com/a-layman
- My web resume: https://jenhsuan.github.io/ALayman/cover.html
- Facebook page: https://www.facebook.com/imalayman
- My latest side project - Daily Learning: https://daily-learning.herokuapp.com/
Top comments (0)