[英]First django rest api call returns request.user as AnonymousUser but further calls return proper user
[英]In Django and DRF, why would an api route request.user return an AnonymousUser instance, while django.contrib.auth.get_user(request) return the user?
让我们走一条非常简单的路线:
class Highscore(APIView):
def get(request):
user = request.user
highscore = user.highscore
return Response({"highschore":highscore})
由于某些未知原因,在某些情况下,尽管用户已通过身份验证并登录(!),但request.user
会返回Anonymous User
实例而不是用户本身。
但是,这可以通过使用 django.contrib.auth 中的get_user
util django.contrib.auth
来绕过。
from django.contrib.auth import get_user
class Highscore(APIView):
def get(request):
user = get_user(request)
highscore = user.highscore
return Response({"highschore":highscore})
可能是什么原因造成的?
重要说明:用户肯定已登录。如此之多,以至于在不同的选项卡中打开管理网站时,它仅从 session 中识别出正确的用户。如果是管理员,则显示管理内容,如果不是,则提供“您登录为...但此视图是为管理员用户保留的”。
我认为您错过了在视图 class 中添加authentication_classes
class 属性,
from rest_framework.permissions import IsAuthenticated
from rest_framework.authentication import SessionAuthentication
class Highscore(APIView):
permission_classes = [IsAuthenticated] authentication_classes = [SessionAuthentication]
def get(self, request):
user = request.user
highscore = user.highscore
return Response({"highschore": highscore})
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.