encode / django-rest-framework

Web APIs for Django. 🎸
https://www.django-rest-framework.org
Other
28.5k stars 6.85k forks source link

Session Cookie Not Being Stored in Browser #9552

Closed JoelOnyedika closed 4 weeks ago

JoelOnyedika commented 1 month ago

Here's a structured version of the GitHub issue, complete with headings for easy copying and pasting:


Title: Session Cookie Not Being Stored in Browser


Description:

I am developing an application using Django as the backend and React as the frontend. I am experiencing an issue where the sessionid cookie is not being stored in the browser after a successful login. As a result, subsequent AJAX requests do not include this cookie, leading to authentication failures.


Problem:


Django Configuration:

SESSION_COOKIE_SAMESITE = 'None'  # Allows cross-origin requests
SESSION_COOKIE_SECURE = False       # Development setup (should be True in production)
SESSION_COOKIE_NAME = 'sessionid'   # Default cookie name
SESSION_COOKIE_HTTPONLY = False       # Recommended for security
SESSION_ENGINE = 'django.contrib.sessions.backends.db'  # Database session storage

My login logic

@method_decorator(ensure_csrf_cookie, name='dispatch')
class LoginView(APIView):
    permission_classes = []  # Allow any, since we're handling authentication manually

    def get(self, request):
        # Return CSRF token for GET requests
        csrf_token = get_token(request)
        return Response({'csrfToken': csrf_token}, status=401)

    def post(self, request):
        try:
            email = request.data.get('email')
            password = request.data.get('password')
            if not email or not password:
                return Response({'error': 'Email and password are required'}, status=status.HTTP_400_BAD_REQUEST)

            try:
                user = CustomUser.objects.get(email=email)
            except CustomUser.DoesNotExist:
                logger.warning(f"Login attempt with non-existent email: {email}")
                return Response({'error': 'Invalid credentials'}, status=status.HTTP_400_BAD_REQUEST)

            user = authenticate(request, username=user.username, password=password)
            if user is not None:
                login(request, user)
                print("Session created for user session_key:", request.session.session_key)
                # request.session.save()
                response_data = UserSerializer(user).data

                csrf_token = get_token(request)

                response = Response({'data': response_data, 'error': None}, status=status.HTTP_200_OK)

                # Set session cookie
                # response.set_cookie(settings.SESSION_COOKIE_NAME, request.session.session_key)

                # Set CSRF token
                response['X-CSRFToken'] = csrf_token                

                response.set_cookie('user_id', str(user.id), samesite='Lax', secure=False, httponly=False, max_age=3600 * 24 * 7)
                response.set_cookie('username', user.username, samesite='Lax', secure=False, httponly=False, max_age=3600 * 24 * 7)

                return response
            else:
                logger.warning(f"Failed login attempt for email: {email}")
                return Response({'error': 'Invalid credentials'}, status=status.HTTP_400_BAD_REQUEST)
        except Exception as e:
            logger.error(f"Unexpected error in login view: {str(e)}")
            return Response({'error': 'An unexpected error occurred'}, status=status.HTTP_500_INTERNAL_SERVER_ERROR)

Steps Taken:

  1. Verified that the login endpoint is being called correctly.
  2. Checked browser settings to ensure cookies are not blocked.
  3. Used credentials: 'include' in AJAX requests to include cookies.

Request for Help:

I am seeking assistance in diagnosing why the sessionid cookie is not being stored in the browser after login and how to resolve this issue.

dineshreddypaidi commented 4 weeks ago

can you share your project repo .. i didnt face any issues and its working...