简体   繁体   English

django rest auth 返回 AnonymousUser

[英]django rest auth returns AnonymousUser

I am using django, drf and django-rest-auth.我正在使用 django、drf 和 django-rest-auth。 I send token from frontend in request header我在请求 header 中从前端发送令牌

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

But this request seems like unauthorized.但这个请求似乎未经授权。 I want to get users information like:我想获取用户信息,例如:

    def get_user_info(request):
        user = request.user

but it returns me AnonymousUser但它返回给我 AnonymousUser

My settings.py:我的设置.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
    }

That's my request headers:那是我的请求标头:

    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

And full server response with headers以及带有标头的完整服务器响应

    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"}

My view function:我的观点 function:

    @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

You are not using Django-rest-framework in right way. 您没有以正确的方式使用Django-rest-framework。 Change your view like this 像这样改变你的看法

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)

You can further see Django-rest docs about views here . 您可以在此处进一步查看有关视图的Django-rest文档。

For my case i had to add @api_view(['POST']) at the begging of the function 就我而言,我必须在@api_view(['POST'])开始时添加@api_view(['POST'])

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

Check settings.py where you gave authentication classes and check for the the authentication you used on views and mentioned on settings.py are the same检查您提供身份验证类的 settings.py,并检查您在视图中使用的身份验证和在 settings.py 中提到的身份验证是否相同

In my case, I have used token authentication in views.py and given basic authentication in settings.py就我而言,我在 views.py 中使用了令牌身份验证,并在 settings.py 中提供了基本身份验证

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 获取用户在Django上返回“ AnonymousUser” - get user returns “AnonymousUser” on django 第一个 django rest api 调用返回 request.user 作为 AnonymousUser 但进一步调用返回正确的用户 - First django rest api call returns request.user as AnonymousUser but further calls return proper user 需要在 Django Rest Framework 中使用 AnonymousUser 登录 - Require Log in with AnonymousUser in Django Rest Framework 调用auth.login()后,Django用户仍然是AnonymousUser - Django user is still AnonymousUser after calling auth.login() 无法使用Django Rest Framework序列化AnonymousUser对象-缺少属性 - Cannot serialize AnonymousUser object using Django Rest Framework - missing attributes 无法使用django rest框架进行身份验证(request.user = AnonymousUser) - Not able to authenticate using the django rest framework (request.user = AnonymousUser) django 登录表单返回 'AnonymousUser' object 没有属性 '_meta' - django login form returns 'AnonymousUser' object has no attribute '_meta' Django Channels consumers.py scope['user'] 返回 anonymousUser - Django Channels consumers.py scope['user'] returns anonymousUser Django oauth2 request.user返回AnonymousUser - Django oauth2 request.user returns AnonymousUser 'AnonymousUser' object 在 django 上不可迭代 - 'AnonymousUser' object is not iterable on django
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM