Django Rest Framework can't get CSRF Token by React

Viewed 131

I've spent six hours on it and I still can't handle getting CSRF Token and Session ID.

I have these two simple functions:

@api_view(["GET"])
@ensure_csrf_cookie
def getCsrf(request):
    return Response({'success': get_token(request)})

@method_decorator(csrf_exempt, name='post')
class LoginView(views.APIView):

    permission_classes = (AllowAny,)

    def post(self, request, format=None):
        serializer = LoginSerializer(data=self.request.data, context={ 'request': self.request })
        serializer.is_valid(raise_exception=True)
        user = serializer.validated_data['user']
        login(request, user)
        return Response(None, status=status.HTTP_202_ACCEPTED)

I have corsheaders installed and I have these settings:

CORS_ALLOWED_ORIGINS = [
    'http://127.0.0.1:3000',
    'http://localhost:3000',
    'http://127.0.0.1:8000',
    'http://localhost:8000',
]

CSRF_TRUSTED_ORIGINS = [
    'http://127.0.0.1:3000', 
    'http://localhost:3000',
    'http://127.0.0.1:8000', 
    'http://localhost:8000',
]

CORS_ALLOW_HEADERS = ('Access-Control-Allow-Origin', 'Access-Control-Allow-Credentials', 'Authorization', 'Content-Type', 'Cache-Control', 'X-Requested-With', 'x-csrftoken')
CORS_ALLOW_CREDENTIALS = True

CSRF_COOKIE_HTTPONLY = False
SESSION_COOKIE_HTTPONLY = False
CSRF_USE_SESSIONS = False

CSRF_COOKIE_SECURE = False
SESSION_COOKIE_SECURE = False
SESSION_COOKIE_SAMESITE = 'None'
CSRF_COOKIE_SAMESITE = 'None'

So, both of those cookies appear in the responses. Neither of them are written in the browser. I've tried everythong I found. This is my React part

axios.defaults.withCredentials = true;

useEffect(() => {
    axios.get(`http://127.0.0.1:8000/csrf/`)
        .then(response => {
            Cookies.set('csrftoken', response['data']['csrf']);
        })
        .catch(error => {
            console.log(error);
        });
}, []);

function onSubmit(e) {
    e.preventDefault();

    let data = {
        username: e.target.username.value,
        password: e.target.password.value
    };

    const config = {     
        headers: { 
            'content-type': 'application/json',
            'Access-Control-Allow-Credentials': 'true',
            'Access-Control-Allow-Origin': 'http://localhost:8000',
            'X-CSRFToken': Cookies.get('csrftoken')
        },
        withCredentials: true,
        crossDomain: true
    }

    axios.post(`http://127.0.0.1:8000/login/`, JSON.stringify(data), config)
        .then(response => {
            console.log(response);
        })
        .catch(error => {
            console.log(error);
        });
}

I'd like not to set cookies by myself as it is now in useEffect, but I can't make it work. I don't know how to get session id, I want it to work as it supposed. I've tried Chrome and Firefox. None of them save those cookies.

0 Answers
Related