403 Forbidden POST Request when trying to log out using React front end with Axios and Django with rest-framework

I keep getting an 403 Forbidden error when trying to log out of the user account. I am able to log in fine, I see in the cookies that there is a sessionID and a csrf token. However every single time without fail I get a 403 forbidden error when trying to log out. I have withCredentials:true and include the csrf token in the header. I have my middleware in the right order, I have all the correct cors-headers configuration and allowed hosts.

When inspecting the network details using F12 I can see that the sessionID cookie is not being sent along with the csrf token. Not sure why? I am at my wits end.

Here is my code for the login and logout front end as well as relevant settings.py code and views.py for logout.

Axios:

import axios from "axios";
axios.defaults.xsrfCookieName = 'csrftoken';
axios.defaults.xsrfHeaderName = 'X-CSRFToken';

const client = axios.create({
  baseURL: "http://127.0.0.1:8000",
  withCredentials: true,
});

export default client;

Login:

function submitLogin(e) {
    e.preventDefault();
    client.post("/api/login/", { username, password }, {
      withCredentials: true,
    })
      .then(function(res) {
        if (res.data.redirect_url) {
          navigate(res.data.redirect_url);
        } else {
          console.error("No redirect URL provided.");
        }
      })

Logout:

function logout(e) {

    e.preventDefault();
    const csrftoken = document.cookie.split('; ').find(row => row.startsWith('csrftoken='))?.split('=')[1];

    client.post("api/logout/", {}, {
        withCredentials: true,
        headers: {
            'X-CSRFToken': csrftoken,
        }
    }).then(res => {
        navigate("/login");
    }).catch(error => {
        console.error('Logout failed:', error);
    });

} 

Settings.py

CORS_ALLOW_CREDENTIALS = True

CORS_ALLOWED_ORIGINS = [
    'http://localhost:5173',  # React development server
    'http://127.0.0.1:5173',  # Alternative localhost address
]
CSRF_TRUSTED_ORIGINS = [
    'http://127.0.0.1:5173',
    'http://localhost:5173',
]

Views.py:

class LogoutView(APIView):
    permission_classes = [IsAuthenticated]

    def post(self, request):
        if request.user.is_authenticated:
            logout(request)
            return Response({'message': 'Logged out successfully'})
        else:
            return Response({'detail': 'User not authenticated'}, status=403)

Please help !

Вернуться на верх