Django Rest Auth返回AnonymousUser。

6
我正在使用Django、DRF和django-rest-auth。我通过请求头从前端发送token。
    {'Authorization': 'Token {$Token}'}

但是这个请求似乎没有授权。我想要获取用户信息,例如:
    def get_user_info(request):
        user = request.user

但是它返回给我AnonymousUser

我的settings.py:

    INSTALLED_APPS = [
        'django.contrib.admin',
        'django.contrib.auth',
        'django.contrib.contenttypes',
        'django.contrib.sessions',
        'django.contrib.messages',
        'django.contrib.staticfiles',
        'core',
        'rest_framework',
        'rest_framework.authtoken',
        'rest_auth',
        'account',
        'corsheaders'
    ]

    REST_FRAMEWORK = {
        'DEFAULT_AUTHENTICATION_CLASSES': (
            'rest_framework.authentication.TokenAuthentication'

        ),

        'DEFAULT_PERMISSION_CLASSES': [
            'rest_framework.permissions.IsAuthenticated',
        ],
        'UNICODE_JSON': True,
        'PAGE_SIZE': 0
    }

这是我的请求头:

    POST /auth/check/ HTTP/1.1
    Host: localhost:8000
    Connection: keep-alive
    Content-Length: 0
    Pragma: no-cache
    Cache-Control: no-cache
    Authorization: Token 7d2ee4481ea0e12bd88f46d57e2e6dab3354d4b7
    Origin: http://localhost:8080
    User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/59.0.3071.115 Safari/537.36
    Content-Type: application/json;charset=utf-8
    Accept: application/json, text/plain, */*
    Referer: http://localhost:8080/
    Accept-Encoding: gzip, deflate, br
    Accept-Language: ru-RU,ru;q=0.8,en-US;q=0.6,en;q=0.4

以及带有头部信息的完整服务器响应

    HTTP/1.1 401 Unauthorized
    Date: Thu, 29 Jun 2017 05:28:06 GMT
    Server: WSGIServer/0.2 CPython/3.4.4
    Access-Control-Allow-Origin: http://localhost:8080
    Vary: Origin, Cookie
    Content-Type: application/json
    X-Frame-Options: SAMEORIGIN
    Transfer-Encoding: chunked

    {"message": "Unauthenticated"}

我的视图函数:

    @csrf_exempt
    def check_auth(request):
        if request.method == 'POST':
            print(request.user)
            if request.user.is_authenticated():
                content = {'message': 'Authenticated'}
                response = JsonResponse(content, status = 200)
                return response
            else:
                content = {'message': 'Unauthenticated'}
                response = JsonResponse(content, status=401)
                return response

1
服务器的完整响应包括头部信息是什么? - Klaus D.
请编辑您的问题并在那里添加响应。 - Klaus D.
如果请求的用户未通过身份验证,request.user将返回AnonymousUser。 - Amar
我在我的问题中附加了响应信息。我已经验证了用户并从后端获取了令牌密钥,并在请求头中使用了该密钥。 - Farid
{'Authorization': 'Token {$Token}'} - 你确定这是正确的吗?看起来你的前端没有正确提供 Authorization 头信息。请添加请求头。 - Sardorbek Imomaliev
3个回答

6
你没有正确使用 Django-rest-framework。请按照以下方式更改你的视图:

你没有正确使用Django-rest-framework。请修改你的视图如下:

class CheckAuth(generics.GenericAPIView):

    def post(self, request):
        print(request.user)
        if request.user.is_authenticated():
             content = {'message': 'Authenticated'}
             return Response(content, status=200)
        else:
             content = {'message': 'Unauthenticated'}
             return Response(content, status=401)

您可以在这里查看Django-rest相关的视图文档。

@Farid 当您使用基于类的视图并在视图中定义了post或get函数时,您将不需要if request.method == 'POST'条件。我已经修改了代码。 - Muhammad Hassan

4
对于我的情况,我需要在函数开头添加@api_view(['POST'])
@csrf_exempt
@api_view(['POST'])
def send_message(request):
    if request.user.is_authenticated:

0

请检查settings.py文件中的身份验证类,并检查在视图中使用的身份验证方式是否与settings.py中提到的相同。

在我的情况下,我在views.py中使用了令牌身份验证,并在settings.py中给出了基本身份验证。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接