django - url 令牌身份验证无法对用户进行身份验证
问题描述
我在注册时未能对我的用户进行身份验证。我已经找到了一次性链接令牌身份验证的解决方案,被篡改了ModelBackend
你可以在这里看到基本的解决方案,我将粘贴我的实现,因为我使用 CBV 作为视图。
自定义ModelBackend
:
from django.contrib.auth.backends import ModelBackend
import logging
from business_accounts.models.my_user import MyUser
logger = logging.getLogger(__name__)
class UrlTokenBackend(ModelBackend):
"""
Custom login backend that will accept token allow click url login
"""
def authenticate(self, request, token=None):
try:
user = MyUser.objects.get(token=token)
except MyUser.DoesNotExist:
logger.warning('My user=%s does not exist', user)
return None
if not user.is_active:
return None
def get_user(self, user_id):
try:
return MyUser.objects.get(pk=user_id)
except MyUser.DoesNotExist:
logger.warning('User with this id=%s does not exists', user_id)
return None
认证中间件注册在这里
AUTHENTICATION_BACKENDS = (
'business_accounts.backends.UrlTokenBackend',
# Needed to login by username in Django admin, regardless of `allauth`
'django.contrib.auth.backends.ModelBackend',
# `allauth` specific authentication methods, such as login by e-mail
'allauth.account.auth_backends.AuthenticationBackend',
)
自定义视图是:
from django.contrib.auth import authenticate, login
from django.shortcuts import redirect
from django.views.generic import View
class UrlGatewayLogin(View):
def get(self, request):
token = request.GET.get('token')
user = authenticate(token=token)
login(request, user)
return redirect('dashboard')
网址是
url(r'^auth/login/', UrlGatewayLogin.as_view(), name='auth-login')
现在我将为登录构建一个 url,就像这样,http:/localhost:8000/auth/login/?token=12323344
所以整个过程将只通过此链接登录用户并将他重定向到仪表板。登录向我显示此错误:
Environment:
Request Method: GET
Request URL: http://localhost:8888/auth/login/?token=eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJleHAiOjE1MjYzNjE5MTksInVzZXJfaWQiOjcwLCJlbWFpbCI6ImFkbWluQGFkbWluLmFpIiwidXNlcm5hbWUiOiJhZG1pbkBhZG1pbi5haSIsIm9yaWdfaWF0IjoxNTI2MzU4OTE5fQ.qyR5SYZ1uO0reVSRjcFdXGGhgfKhdu1eU277UAGU5l8
Django Version: 1.8.5
Python Version: 3.4.2
Installed Applications:
['django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'django.contrib.sites',
'allauth',
'allauth.account',
'allauth.socialaccount',
'allauth.socialaccount.providers.facebook',
'allauth.socialaccount.providers.twitter',
'allauth.socialaccount.providers.foursquare',
'allauth.socialaccount.providers.google',
'rest_framework',
'rest_framework_swagger',
'django_filters',
'corsheaders',
'gunicorn',
'googleads',
'django_nose',
'webpack_loader',
'common',
'business_accounts',
'search',
'platforms_search',
'locations',
'reviews',
'socialmedia',
'inbox',
'stats',
'usermanagement',
'connect',
'dashboard',
'freetrial',
'billing',
'demo',
'social_tickets',
'external',
'test_account']
Installed Middleware:
('django.contrib.sessions.middleware.SessionMiddleware',
'corsheaders.middleware.CorsMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.auth.middleware.SessionAuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
'django.middleware.security.SecurityMiddleware',
'django.middleware.common.CommonMiddleware')
Traceback:
File "/srv/bspotted.net/venv/lib/python3.4/site-packages/django/core/handlers/base.py" in get_response
132. response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "/srv/bspotted.net/venv/lib/python3.4/site-packages/django/views/generic/base.py" in view
71. return self.dispatch(request, *args, **kwargs)
File "/srv/bspotted.net/venv/lib/python3.4/site-packages/django/views/generic/base.py" in dispatch
89. return handler(request, *args, **kwargs)
File "/srv/bspotted.net/app/business_accounts/views/url_gateway_login.py" in get
10. login(request, user)
File "/srv/bspotted.net/venv/lib/python3.4/site-packages/django/contrib/auth/__init__.py" in login
111. request.session[SESSION_KEY] = user._meta.pk.value_to_string(user)
File "/srv/bspotted.net/venv/lib/python3.4/site-packages/django/utils/functional.py" in inner
226. return func(self._wrapped, *args)
Exception Type: AttributeError at /auth/login/
Exception Value: 'AnonymousUser' object has no attribute '_meta'
那么有人可以解释为什么会发生这种情况以及我该如何克服这个问题,谢谢。
解决方案
authenticate()
应该返回用户对象:
class UrlTokenBackend(ModelBackend):
"""
Custom login backend that will accept token allow click url login
"""
def authenticate(self, request, token=None):
try:
user = MyUser.objects.get(token=token)
except MyUser.DoesNotExist:
logger.warning('My user=%s does not exist', user)
return None
if not user.is_active:
return None
return user
推荐阅读
- javascript - 失去焦点时提交表单
- mysql - 选择哪个用户有更多产品
- c# - 如何从 Azure Function App 中的请求正文中检索字节数据
- rxjs - 无法从 rxjs 5.0 取消 observable
- java - 自定义 Maven 插件 - 阅读 maven-metadata.xml?
- gradle - 如何在 Gradle Kotlin DSL 中使用类型安全的额外属性
- amazon-web-services - 当 ECS 中有多个仅在命令上有所不同的服务时,如何避免 terraform 中的重复?
- android - Cipher.doFinal 之后的 Android AES 加密丢失字节
- r - Shiny中的对象问题
- html - Css - 移动设备上的图像被破坏