【问题标题】:django rest auth returns AnonymousUserdjango rest auth 返回 AnonymousUser
【发布时间】:2017-12-02 17:33:14
【问题描述】:

我正在使用 django、drf 和 django-rest-auth。我在请求标头中从前端发送令牌

    {'Authorization': 'Token {$Token}'}

但这个请求似乎未经授权。我想获取用户信息,例如:

    def get_user_info(request):
        user = request.user

但它返回给我 AnonymousUser

我的设置.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

【问题讨论】:

  • 服务器的准确、完整响应是什么?标题?
  • 请编辑您的问题并在此处添加回复。
  • request.user 如果请求用户未通过身份验证,则返回 AnonymousUser
  • 在我的问题中附加了回复信息。我已经对用户进行身份验证并从后端获取令牌密钥并在请求标头中使用此密钥
  • {'Authorization': 'Token {$Token}'} - ?你确定这是正确的吗?看起来您的前端没有提供 Authorization 标头正确。也添加请求标头

标签: python django django-rest-framework django-rest-auth


【解决方案1】:

对于我的情况,我必须在函数的请求处添加@api_view(['POST'])

@csrf_exempt
@api_view(['POST'])
def send_message(request):
    if request.user.is_authenticated:

【讨论】:

    【解决方案2】:

    您没有以正确的方式使用 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)
    

    您可以进一步查看有关视图 here 的 Django-rest 文档。

    【讨论】:

    • @Farid 当您使用基于类的视图并在视图中定义了 post 或 get 函数时,您将不需要 if request.method == 'POST 条件。我修改了代码。
    猜你喜欢
    • 2017-01-02
    • 2017-11-22
    • 1970-01-01
    • 2021-02-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-04-07
    • 1970-01-01
    相关资源
    最近更新 更多