I'm having trouble setting cookies with response.set_cookies it return empty dictionary in request.COOKIES in my Django and React.js using axios [duplicate]
I am developing authentication application using django rest framework and React.js with JWT and it works with login and registering user but when I want to access logged in user detail it says un authenticated it can't get Cookie from request.COOKIES.get("jwt") it returns empty dictionary and it also said in frontend Response Headers
This Set-Cookie headers didn't specify a "SameSite" attribute and was defaulted to "SameSite = Lax," and was blocked because it came from a cross-site response...
Here is the View.py
...
class LoginView(APIView):
def post(self, request):
email = request.data["email"]
password = request.data["password"]
user = User.objects.filter(email=email).first()
if user is None:
raise AuthenticationFailed("Incorrect Email!")
if not user.check_password(password):
raise AuthenticationFailed("Incorrect Password!")
payload = {
'id': user.id,
'exp': datetime.datetime.utcnow() + datetime.timedelta(minutes=60),
'iat': datetime.datetime.utcnow()
}
token = jwt.encode(payload, 'secret', algorithm='HS256')
response = Response()
response.set_cookie(key='jwt', value=token, httponly=True)
response.data = {
'jwt': token
}
return response
class UserView(APIView):
def get(self, request):
token = request.COOKIES.get("jwt")
print(request.COOKIES)
if not token:
raise AuthenticationFailed("UnAuthenticated 1!")
try:
payload = jwt.decode(token, 'secret', algorithms=['HS256'])
except jwt.ExpiredSignatureError:
raise AuthenticationFailed("UnAuthenticated 2!")
user = User.objects.filter(id=payload['id']).first()
serializer = UserSerializer(user)
return Response(serializer.data)
...
Here is settings.py
...
ALLOWED_HOSTS = []
# Application definition
INSTALLED_APPS = [
...
'corsheaders',
'rest_framework',
...
]
MIDDLEWARE = [
"django.middleware.security.SecurityMiddleware",
"django.contrib.sessions.middleware.SessionMiddleware",
"corsheaders.middleware.CorsMiddleware",
"django.middleware.common.CommonMiddleware",
"django.middleware.csrf.CsrfViewMiddleware",
"django.contrib.auth.middleware.AuthenticationMiddleware",
"django.contrib.messages.middleware.MessageMiddleware",
"django.middleware.clickjacking.XFrameOptionsMiddleware",
]
...
CORS_ORIGIN_WHITELIST = [
'http://localhost:3000',
'http://127.0.0.1:3000',
]
CORS_ALLOW_ALL_ORIGINS = True
CORS_ALLOW_CREDENTIALS = True
What could be causing this? Am I missing some setting in React? I'm using axios to make the calls, with the only header being "Content-Type": "application/json"