【问题标题】:request.user.is_authenticated is always false in Django rest frameworkrequest.user.is_authenticated 在 Django 休息框架中总是假的
【发布时间】:2019-04-15 15:44:30
【问题描述】:

我在 drf 中使用 allauth 进行身份验证。我能够注册新用户并使用凭据登录。 登录 api 返回响应如下:

{
 "key" : "<some token>"
}

现在我还有 1 个 API,其代码是

    from django.http import HttpResponse
    def lol(request):
        if request.user.is_authenticated:
            return HttpResponse("Authenticated")
        else:
            return HttpResponse("Not Authenticated")

但这总是返回未验证 我的 api 调用看起来像这样

这是我的 settings.py 中已安装应用程序的列表

INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'rest_framework',
'rest_framework.authtoken',
'rest_auth',
'django.contrib.sites',
'allauth',
'allauth.account',
'rest_auth.registration',

'api.user',
'api.activity',
]

【问题讨论】:

    标签: django python-3.x django-rest-framework django-allauth


    【解决方案1】:

    您似乎正在使用功能视图?如果是这样,您是否将 @api_view 装饰器添加到视图中?

    如果是这样,您是否添加了 authentication_classes=[TokenAuthentication] 关键字参数?这对于使令牌身份验证起作用是必不可少的。

    或者在settings.py中设置以下内容:

    REST_FRAMEWORK = {
        'DEFAULT_AUTHENTICATION_CLASSES': [
            'rest_framework.authentication.TokenAuthentication'
        ]
    }
    

    【讨论】:

    • 非常感谢!我错过了@api_view。
    猜你喜欢
    • 2013-04-08
    • 2021-11-26
    • 1970-01-01
    • 1970-01-01
    • 2015-02-25
    • 2016-04-25
    • 2016-03-23
    相关资源
    最近更新 更多