DEV Community ๐Ÿ‘ฉโ€๐Ÿ’ป๐Ÿ‘จโ€๐Ÿ’ป

DEV Community ๐Ÿ‘ฉโ€๐Ÿ’ป๐Ÿ‘จโ€๐Ÿ’ป is a community of 964,423 amazing developers

We're a place where coders share, stay up-to-date and grow their careers.

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

Posted on

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!

Top comments (0)

๐Ÿ‘‹ Hey, my name is Noah and Iโ€™m the one who set up this ad. My job is to get you to join DEV, so if you fancy doing me a favor, Iโ€™d love for you to create an account.

If you found DEV from searching around, here are a couple of our most popular articles on DEV: