I am using a Django DRF backend with SessionAuthentication and a NextJS frontend. They are hosted on different ports. I am trying to use the django login function to automatically log the user in when creating an account. When I run this, the sessionid and csrf cookie gets saved into cookies but upon refresh they disappear.
Before refresh:
cookies in dev tools
After refresh:
cookies gone after refresh
Relevant settings.py settings:
CORS_ALLOW_CREDENTIALS = True
CSRF_USE_SESSIONS = True
SESSION_COOKIE_SECURE = True
SESSION_COOKIE_SAMESITE = 'None'
CORS_ALLOWED_ORIGINS = [
"https://localhost:3000",
]
CSRF_TRUSTED_ORIGINS = {
"https://localhost:3000"
}
View used:
class UserView(APIView):
renderer_classes = [JSONRenderer]
permission_classes = [
permissions.AllowAny
]
decorators = [sensitive_variables('password'), ensure_csrf_cookie]
@method_decorator(decorators)
def post(self, request, format=None):
"""Create User"""
serializer = UserSerializer(data=request.data)
if serializer.is_valid():
serializer.save()
username = serializer.validated_data['username']
password = serializer.validated_data['password']
user = authenticate(username=username, password=password)
if user:
login(request, user)
return Response(data={'response': 'Successfully created account'}, status=status.HTTP_201_CREATED)
return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
Request:
const response = await fetch(`https://127.0.0.1:8000/user/`, {
method: 'POST',
mode: 'cors',
credentials: 'include',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify(data)
});
Both django server and NextJS are running on a dev SSL certificate so both have https.