Django request.user在没有login_required装饰器的视图中是匿名的

时间:2017-12-11 13:49:57

标签: django authentication django-allauth

我正在使用django-allauth作为auth后端的Django(v2.0)应用程序。我将逐步解释我的问题:

  1. 用户登录 - >用户重定向到主页(无法登录时无法访问主页)
  2. 在主页(登录后)中,对服务器中的特定视图进行了多次调用 例如:https://mywebsite.com/api/getstuff/123
  3. 问题: getstuff返回/打印供未登录用户使用的数据。
  4. getstuff在urls.py中定义为:

    url(r'^api/getstuff/(?P<hash_code>[a-zA-Z0-9]{3})$', views.getstuff, name='getstuff')

    在views.py中的

    :( views.getstuff

    @csrf_protect
    @ensure_csrf_cookie
    def getstuff(request,hash_code):
        if request.user.is_authenticated:
            #do stuff....
            print('user is authenticated!')
            return HttpResponse(hash_code+'foo-auth')
        else:
            #do other stuff..
            print('user is NOT authenticated')
            return HttpResponse(hash_code+'foo-un_auth')
    

    我只看到user is NOT authenticated在我的情况下被打印。由于用户已经登录,输出不应该是user is authenticated吗? request.user对象是AnonymousUser对象。我提出的所有请求均来自https

    来自settings.py的一些配置:

    CSRF_USE_SESSIONS = True
    CSRF_COOKIE_SECURE = True #tried removing this, still same result as above
    
    INSTALLED_APPS = [
        'django.contrib.admin',
        'django.contrib.auth',
        'django.contrib.contenttypes',
        'django.contrib.sessions',
        'django.contrib.messages',
        'django.contrib.staticfiles',
        'django.contrib.sites',
        'django_extensions',
        'django.contrib.sitemaps',
        'mysite.core',
        'bootstrapform',
        'allauth',
        'allauth.account',
        'allauth.socialaccount',
        'allauth.socialaccount.providers.facebook',
        'allauth.socialaccount.providers.google',
        'allauth.socialaccount.providers.github',
        'allauth.socialaccount.providers.twitter',
        'embed',
        'channels',
        'djcelery'
    ]
    
    MIDDLEWARE = [
        'django.middleware.security.SecurityMiddleware',
        'django.contrib.sessions.middleware.SessionMiddleware',
        'django.middleware.common.CommonMiddleware',
        'django.middleware.csrf.CsrfViewMiddleware',
        'django.contrib.auth.middleware.AuthenticationMiddleware',
        'django.contrib.messages.middleware.MessageMiddleware',
        'django.middleware.clickjacking.XFrameOptionsMiddleware',
    ]
    
    AUTHENTICATION_BACKENDS = (
        "allauth.account.auth_backends.AuthenticationBackend",
    )
    

    我在访问网站并登录前尝试清除缓存 - 结果仍然相同 我错过了什么吗?可能是什么问题?

1 个答案:

答案 0 :(得分:1)

您对if request.user.is_authenticated:的使用很好。更改图片src标记以使用您登录的域。

<img src="/api/getstuff/123">