I am using Django(REST FrameWork, SimpleJWT) and React for my project. For autentication I am using JWT method.
According to some articles, storing and sending REFRESH TOKEN in HttpOnly Cookie is the a best and secure way. Since I am learning WebDevelopment I can’t able to find any source to about it.
This is my views.py
class MyTokenObtainPairView(TokenObtainPairView): serializer_class = MyTokenObtainPairSerializer def post(self, request, *args, **kwargs): try: response = super().post(request) except InvalidToken: return Response({'Invalid or expired token'}) refresh_token = RefreshToken.for_user(request.user) response.set_cookie('refresh_token', refresh_token, httponly=True) return response class RegisterView(generics.CreateAPIView): queryset = User.objects.all() permission_classes = (AllowAny,) serializer_class = RegisterSerializer class LogoutView(generics.CreateAPIView): def post(self, request): refresh_token = request.data['refresh_token'] token = RefreshToken(refresh_token) token.blacklist() return Response({'Logout':'Successfullly'})
as you can i even tried to over write the post method in MyTokenObtainPairView.
This is my urls.py
path('api/login/', MyTokenObtainPairView.as_view(), name="token_obtain_pair"), path('api/token/refresh/', TokenRefreshView.as_view(), name="token_refresh"), path('api/register/', RegisterView.as_view(), name="auth_register"), path('api/logout/', LogoutView.as_view(), name="logout"),
This is my settings.py
SIMPLE_JWT = { 'ACCESS_TOKEN_LIFETIME': timedelta(hours=5), 'REFRESH_TOKEN_LIFETIME': timedelta(days=2), 'ROTATE_REFRESH_TOKENS': True, 'BLACKLIST_AFTER_ROTATION': True, 'UPDATE_LAST_LOGIN': False, 'ALGORITHM': 'HS256', 'VERIFYING_KEY': None, 'AUDIENCE': None, 'ISSUER': None, 'JWK_URL': None, 'LEEWAY': 0, 'AUTH_HEADER_TYPES': ('Bearer',), 'AUTH_HEADER_NAME': 'HTTP_AUTHORIZATION', 'USER_ID_FIELD': 'id', 'USER_ID_CLAIM': 'user_id', 'USER_AUTHENTICATION_RULE': 'rest_framework_simplejwt.authentication.default_user_authentication_rule', 'AUTH_TOKEN_CLASSES': ('rest_framework_simplejwt.tokens.AccessToken',), 'TOKEN_TYPE_CLAIM': 'token_type', 'TOKEN_USER_CLASS': 'rest_framework_simplejwt.models.TokenUser', 'JTI_CLAIM': 'jti', 'SLIDING_TOKEN_REFRESH_EXP_CLAIM': 'refresh_exp', 'SLIDING_TOKEN_LIFETIME': timedelta(hours=5), 'SLIDING_TOKEN_REFRESH_LIFETIME': timedelta(days=2), }
I am expecting a way to store and send REFRESH TOKEN in HttpOnly Cookie to frontend when user logins or refresh it.
Advertisement
Answer
You might find an answer in this thread:
How to store JWT tokens in HttpOnly cookies with DRF djangorestframework-simplejwt package?
This GitHub comment also suggests a similar solution.