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
JavaScript
x
23
23
1
class MyTokenObtainPairView(TokenObtainPairView):
2
serializer_class = MyTokenObtainPairSerializer
3
def post(self, request, *args, **kwargs):
4
try:
5
response = super().post(request)
6
except InvalidToken:
7
return Response({'Invalid or expired token'})
8
refresh_token = RefreshToken.for_user(request.user)
9
response.set_cookie('refresh_token', refresh_token, httponly=True)
10
return response
11
12
class RegisterView(generics.CreateAPIView):
13
queryset = User.objects.all()
14
permission_classes = (AllowAny,)
15
serializer_class = RegisterSerializer
16
17
class LogoutView(generics.CreateAPIView):
18
def post(self, request):
19
refresh_token = request.data['refresh_token']
20
token = RefreshToken(refresh_token)
21
token.blacklist()
22
return Response({'Logout':'Successfullly'})
23
as you can i even tried to over write the post method in MyTokenObtainPairView.
This is my urls.py
JavaScript
1
5
1
path('api/login/', MyTokenObtainPairView.as_view(), name="token_obtain_pair"),
2
path('api/token/refresh/', TokenRefreshView.as_view(), name="token_refresh"),
3
path('api/register/', RegisterView.as_view(), name="auth_register"),
4
path('api/logout/', LogoutView.as_view(), name="logout"),
5
This is my settings.py
JavaScript
1
33
33
1
SIMPLE_JWT = {
2
'ACCESS_TOKEN_LIFETIME': timedelta(hours=5),
3
'REFRESH_TOKEN_LIFETIME': timedelta(days=2),
4
'ROTATE_REFRESH_TOKENS': True,
5
'BLACKLIST_AFTER_ROTATION': True,
6
'UPDATE_LAST_LOGIN': False,
7
8
'ALGORITHM': 'HS256',
9
10
'VERIFYING_KEY': None,
11
'AUDIENCE': None,
12
'ISSUER': None,
13
'JWK_URL': None,
14
'LEEWAY': 0,
15
16
'AUTH_HEADER_TYPES': ('Bearer',),
17
'AUTH_HEADER_NAME': 'HTTP_AUTHORIZATION',
18
'USER_ID_FIELD': 'id',
19
'USER_ID_CLAIM': 'user_id',
20
'USER_AUTHENTICATION_RULE': 'rest_framework_simplejwt.authentication.default_user_authentication_rule',
21
22
'AUTH_TOKEN_CLASSES': ('rest_framework_simplejwt.tokens.AccessToken',),
23
'TOKEN_TYPE_CLAIM': 'token_type',
24
'TOKEN_USER_CLASS': 'rest_framework_simplejwt.models.TokenUser',
25
26
'JTI_CLAIM': 'jti',
27
28
'SLIDING_TOKEN_REFRESH_EXP_CLAIM': 'refresh_exp',
29
'SLIDING_TOKEN_LIFETIME': timedelta(hours=5),
30
'SLIDING_TOKEN_REFRESH_LIFETIME': timedelta(days=2),
31
}
32
33
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.