my request.user is always AnonymousUser

this is my login.py

import json

from django.http import JsonResponse
from django.contrib.auth import authenticate,login


def signin(request):
    data = json.loads(request.body.decode('utf-8'))
    username = data.get('username').strip()
    password = data.get('password').strip()
    user = authenticate(request,username=username,password=password)
    if not user:
        return JsonResponse({
                'result':"username or password not correct"
            })
    login(request,user)
    print(user)
    return JsonResponse({
        'result':"success",
        })

this is my getinfo.py

import json

from django.http import JsonResponse
from django.views.decorators.csrf import csrf_exempt

from nlp_back.models.ailaber.ailaber import Ailaber


def getinfo_web(request):
    user = request.user
    print(user)
    if not user.is_authenticated:
        return JsonResponse({
            "result": "unlogged",
                    })
    else:
        player = Ailaber.objects.get(user=user)
        return JsonResponse({
            "result": "success",
            "username": player.user.username,
            "photo": player.photo,
            })
def getinfo(request):
    return getinfo_web(request)

this is my vue3 code

await axios.post('http://localhost:8000/settings/login/',{
      username:form.username,
      password:form.password,
    }).then(res=>{
      if(res.data.result==='success'){
        axios.post('http://localhost:8000/settings/getinfo/').then(res=>{
        if(res.data.result==='unlogged'){
          console.log(res);
          
        }else{
          console.log(res);
          
        }
      }).catch(e=>{
        console.log(e)
      })
        //router.push({path:'/'});
      }else{
        login_text.value = res.data.result;
      }
    }).catch(e=>{
      console.log(e);
    })

the request.user is always AnonymousUser after login,why?

I’d start by adding a couple more print statements to your signin view to verify what data you’re seeing at every step. Check to make sure that data is what you expect it to be. Check that the username and password being retrieved from data are what you expect them to be. Check to see what user is immediately after the authenticate function.

In other words, don’t make assumptions about the data you have or are receiving.

thank you,after

user = authenticate(request,username=username,password=password)
print(user)

the user is correct,but in getinfo.py,the request.user is AnonymousUser

Then the next thing to check would be to see what the session id cookie is during this sequence.

  • What is being submitted during the login request,
  • What is being returned in that response,
  • What you’re then sending back in your follow-up request to getinfo_web.

Hi.

If your vue3 code is not served by the same domain as your django API (i.e. localhost:8000), you may be facing a cross domain issue.

If so, to ensure session cookie is sent in subsequent requests after login, you need to set withCredentials attribute to true in the request. E.g.

axios.post('http://localhost:8000/settings/getinfo/', { withCredentials: true })

You may also enforce this behaviour for every request by setting
axios.defaults.withCredentials

You’ll also have to correcty set CORS settings on django side (see Be logged in mutiple sites - #13 by antoinehumbert)

But, as stated by Ken, checking requests/responses headers from your browser should help in identifying the root cause of the problem

thank you so much,after adding the axios.defaults.withCredentials,there is an error in my browser:Access to XMLHttpRequest at 'http://localhost:8000/settings/login/' from origin 'http://localhost:8080' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: The value of the 'Access-Control-Allow-Credentials' header in the response is '' which must be 'true' when the request's credentials mode is 'include'. The credentials mode of requests initiated by the XMLHttpRequest is controlled by the withCredentials attribute.

This is where CORS configuration on the backend come into play.

See my previous post and define at least following settings:

CORS_ALLOWED_ORIGINS = ["http://the.domain.of.vue.app"]
CORS_ALLOW_CREDENTIALS = True

But, before going further, can you tell what is the domain serving the Vue app ? And, did you checked the request/response contents in The original scenario ?

my vue app is running by node.js in localhost,after adding

CORS_ALLOWED_ORIGINS = ["http://localhost:8080"]
CORS_ALLOW_CREDENTIALS = True

there is an error in my backend Forbidden (CSRF cookie not set.): /settings/getinfo/

There is actually no reason for your get_info view to be called in post, so you may consider using axios.get instead of axios.post for this one.

If you really want to do POST, you can wrap your view with @csrf_exempt decorator

thank you so much,my problem has been solved now.

sorry,there is still problem with my code,my vue3 code

await axios.get('http://localhost:8000/settings/login/',{
      username:form.username,
      password:form.password,
    }).then(res=>{
      if(res.data.result==='success'){
        router.push({path:'/'});
      }else{
        login_text.value = res.data.result;
      }
    }).catch(e=>{
      console.log(e);
    })

has send password and username,but request.GET is <QueryDict: {}>

You must use .post for the login view, not get. I told using .get for the getinfo view only.

If you have a csrf error with the login view, wrap it with @csrf_exempt (see Cross Site Request Forgery protection | Django documentation | Django)

thank you,I changed the vue3 code to

params:{
        username:form.username,
        password:form.password,
      }

and the request.GET can get the username and password.