django rest auth返回AnonymousUser

时间:2017-06-29 06:36:30

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

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

    {'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

2 个答案:

答案 0 :(得分:3)

您没有正确使用Django-rest-framework。像这样改变你的观点

key()

您可以进一步查看关于观看{{3}}的Django-rest文档。

答案 1 :(得分:0)

对于我来说,我必须在函数的开头添加@api_view(['POST'])

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