1

I'm using Django and React to create a login page. When the user clicks on the submit button, I send an Axios POST request to my Django server to authenticate and login. In the login function, printing request.user works as intended. But as soon as the scope of the function is left, printing request.user prints AnonymousUser. I've talked to some people about it and they seem to think it's because cookies aren't persisting, but we haven't been able to solve the problem. Any guidance would be appreciated.

// REACT FORM 
function submitHandler(event) {
    event.preventDefault();
    const state = login ? "login" : "signup";

    axios
        .post(`http://localhost:8000/auth/${state}`, {
            username: username,
            password: password,
        })
        .then((response) => {
            setRedirectMessage(response.data);
            axios
                .post("http://localhost:8000/auth/user")
        })
        .catch((err) => alert(err.response.data));
}
# LOGIN REQUEST (/auth/login)
@require_POST
@csrf_exempt
def auth_login(request):
    if request.user.is_authenticated:
        return HttpResponseBadRequest("You are already logged in")
    username, password = get_credentials(request)
    user = authenticate(username=username, password=password)
    if user is None:
        return HttpResponseBadRequest("Those credentials do not exist")
    login(request, user)
    print(user) # PRINTS CORRECTLY
    print(request.user) # PRINTS CORRECTLY
    return HttpResponse("You have successfully logged in with username " + username)
# GET REQUEST TO CHECK LOGIN STATE (auth/user)
@csrf_exempt
def get_user(request):
    print(request.user)
    return HttpResponse("Hey there")
Sam Liu
  • 157
  • 1
  • 8
  • Does this answer your question? [Make Axios send cookies in its requests automatically](https://stackoverflow.com/questions/43002444/make-axios-send-cookies-in-its-requests-automatically) – Abdul Aziz Barkat Jun 23 '21 at 14:27
  • @AbdulAzizBarkat Thanks for the link. I'll give it a try and let you know. – Sam Liu Jun 23 '21 at 14:34
  • @AbdulAzizBarkat Ok I've done some looking into it. After setting `withCredentials: true`, I get the following error: `Credentials flag is true, but Access-Control-Allow-Credentials is not "true".`, so I attempted whitelisting my front end in `settings.py` like so: `CORS_ORIGIN_WHITELIST = ['http://localhost:3000']` but the error still persists – Sam Liu Jun 23 '21 at 15:04

1 Answers1

2

The following line is needed in settings.py:

CORS_ALLOW_CREDENTIALS = True

https://pypi.org/project/django-cors-headers/

Tomas_S
  • 36
  • 3