DEV Community

Cover image for Day 30 of #100DaysOfCode: Refresh JWT in the HttpOnly cookie
Jen-Hsuan Hsieh
Jen-Hsuan Hsieh

Posted on • Edited on

2 1

Day 30 of #100DaysOfCode: Refresh JWT in the HttpOnly cookie

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'),

]
Enter fullscreen mode Exit fullscreen mode

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()   

Enter fullscreen mode Exit fullscreen mode
  • Edit the urls.py
...
from .views import renew_token

urlpatterns = [
    ...,
    path('api/renew-token/', renew_token, name='renew-token')
]

Enter fullscreen mode Exit fullscreen mode

That's it!

Articles

There are some of my articles. Feel free to check if you like!

Sentry blog image

How I fixed 20 seconds of lag for every user in just 20 minutes.

Our AI agent was running 10-20 seconds slower than it should, impacting both our own developers and our early adopters. See how I used Sentry Profiling to fix it in record time.

Read more

Top comments (0)

AWS GenAI LIVE image

Real challenges. Real solutions. Real talk.

From technical discussions to philosophical debates, AWS and AWS Partners examine the impact and evolution of gen AI.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay