How to use http only cookie with django rest framework?
Asked Answered
O

1

7

I read about some of the issues related to storing jwt token in local storage that's why I am trying to store token in http-only cookie. I am using following approach.

from rest_framework.views import APIView
from rest_framework.response import Response
import jwt
from django.conf import settings
from rest_framework import status

class LoginView(APIView):
    def post(self, request, format=None):
        email = request.data['email']
        password = request.data['password']

        # dummy user authentication
        if email == 'email' and password == 'password':
            encoded = jwt.encode(
                {'email': email}, settings.SECRET_KEY, algorithm='HS256')

            response = Response()
            response.set_cookie(key='token', value=encoded, httponly=True)
            response.data = {
                'user': email,
            }
            return response
        else:
            return Response({'error': 'wrong credentials'}, status=status.HTTP_401_UNAUTHORIZED)

Question 1: Is this a right approach to set httponly cookie using django rest framework?

response = Response()
response.set_cookie(key='token', value=encoded, httponly=True)
response.data = {
    'user': email,
}
return response

After this every time when I am getting a request from the client (using React with axios) I am able to access the cookie using request.COOKIES['token'] in django view. Using this I can write my own function for authentication but I don't think it is a perfect approach because generally, we pass token in Authorization headers which sets the request.user based on the token and if I use this approach I will not be unable to use postman for testing and django rest frameworks IsAuthenticated class also looks for request.user and request.user.is_authenticated for True value.

Question 2: How to pass the token as an Authorization header from the client if the token is stored in httponly cookie?

Please help me. I am a bit confused with the workflow of http-only cookie because generally I used to store token in local storage and it was easier to retrieve the token and pass it from the frontend.

Overblown answered 12/8, 2020 at 4:44 Comment(3)
did you get a solution to this problem?Plenish
No yet, @ArkaGhoshOverblown
@ArkaGhosh you can follow this procoding.org/jwt-token-as-httponly-cookie-in-djangoOverblown
C
1

Answer 1:

Yes this is a good approach to set httponly flag cookie because httpOnly cookies can't be accessed by JavaScript. Without httponly flag cookie it vulnerable to CSRF attacks.

While localStorage is accessible through javascript (as opposed to HttpOnly cookies) and makes it vulnerable to XSS attacks. So I think using httponly cookies + CSRF is the most secure way even in TokenAuthentication for storing tokens on client. However, this is not very well supported by DRF and other popular libraries that I've looked at.

Answer 2:

No, because you can not retrieve httponly cookie by using javascript from client side.It's big Advantage of httponly cookie.So this cookie only accessible through http(s) request. Make sure withCredentials is True for both side.

I personally use djangorestframework-simplejwt package to set (access token + CSRF token) in httponly cookie and get by using CustomAuthentication class. Check this

Cabezon answered 18/2, 2021 at 20:16 Comment(1)
What if you want to refresh token?Chemash

© 2022 - 2024 — McMap. All rights reserved.