loading...
Cover image for Day 30 of #100DaysOfCode: Refresh JWT in the HttpOnly cookie

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

jenhsuan profile image Sean Hsieh ・1 min read

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!

Posted on by:

jenhsuan profile

Sean Hsieh

@jenhsuan

5+ year work experience in the software engineering field. Near 2-year work experience with front-end JavaScript framework like React.js, Knockout.js. and Microsoft solution.

Discussion

markdown guide