我正在使用django-allauth作为auth后端的Django(v2.0)应用程序。我将逐步解释我的问题:
https://mywebsite.com/api/getstuff/123
getstuff
返回/打印供未登录用户使用的数据。 getstuff
在urls.py中定义为:
url(r'^api/getstuff/(?P<hash_code>[a-zA-Z0-9]{3})$', views.getstuff, name='getstuff')
:( 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",
)
我在访问网站并登录前尝试清除缓存 - 结果仍然相同 我错过了什么吗?可能是什么问题?
答案 0 :(得分:1)
您对if request.user.is_authenticated:
的使用很好。更改图片src
标记以使用您登录的域。
<img src="/api/getstuff/123">