【发布时间】:2015-12-28 18:18:49
【问题描述】:
我的 Django 应用程序和 django-rest-framework 目前遇到以下问题。
我根据以下内容编写了一个 CustomAuthToken 视图: Django rest framework: Obtain auth token using email instead username
帐户/views.py
class UserView(APIView):
def get(self, request):
users = Customer.objects.all()
serializer = CustomerSerializer(users, many=True)
return Response(serializer.data)
class ObtainAuthToken(APIView):
throttle_classes = ()
permission_classes = ()
parser_classes = (
FormParser,
MultiPartParser,
JSONParser,
)
renderer_classes = (JSONRenderer,)
def post(self, request):
# Authenticate User
c_auth = CustomAuthentication()
customer = c_auth.authenticate(request)
token, created = Token.objects.get_or_create(user=customer)
content = {
'token': unicode(token.key),
}
return Response(content)
我的主要 urls.py:
from rest_framework.urlpatterns import format_suffix_patterns
from account import views as user_view
urlpatterns = [
url(r'users/$', user_view.UserView.as_view()),
url(r'^api-token-auth/', user_view.ObtainAuthToken.as_view()),
url(r'^auth/', include('rest_framework.urls',
namespace='rest_framework')),
]
urlpatterns = format_suffix_patterns(urlpatterns)
我的自定义 authentication.py:
from django.contrib.auth.hashers import check_password
from rest_framework import authentication
from rest_framework import exceptions
from usercp.models import Customer
class CustomAuthentication(authentication.BaseAuthentication):
def authenticate(self, request):
email = request.POST.get('email')
password = request.POST.get('password')
if not email:
return None
if not password:
return None
try:
user = Customer.objects.get(email=email)
if check_password(password, user.password):
if not user.is_active:
msg = _('User account is disabled.')
customer = user
else:
msg = _('Unable to log in with provided credentials.')
customer = None
except Customer.DoesNotExist:
msg = 'No such user'
raise exceptions.AuthenticationFailed(msg)
return customer
取自我的 settings.py:
REST_FRAMEWORK = {
'DEFAULT_PERMISSION_CLASSES': [
'rest_framework.permissions.IsAuthenticated'
],
'DEFAULT_AUTHENTICATION_CLASSES': (
'rest_framework.authentication.TokenAuthentication',
)
}
当我发送我的 curl 请求时:
curl -H "Accept: application/json; indent=4" -H "Authorization: Token bd97803941a1ede303e4fda9713f7120a1af656c" http://127.0.0.1:8000/users
我收到“拒绝访问”。
登录工作正常,我收到了返回的令牌。
但是,我无法访问我的用户视图。我不太确定问题是什么。我需要更改 TokenAuthentication 的设置吗?我不这么认为。由于用户在数据库中设置正确,即使我使用从 AbstractUser 继承的自定义用户对象。从文档 (http://www.django-rest-framework.org/api-guide/authentication/#setting-the-authentication-scheme) 来看,我认为我做的一切都是正确的,因为他们使用相同的请求标头,间距是正确的,我认为没有任何编码问题。
【问题讨论】:
-
你调试你的
authenticate方法了吗?检查是否按预期工作。 -
你将如何调试它?如果我向它发送了正确的登录凭据,我会收到一个令牌。如果我发送了错误的凭据,我将不会取回令牌。
-
使用this`import pdb`然后把它放到你的方法
pdb.set_trace()中,现在你可以使用服务器控制台调试它了。
标签: python django django-rest-framework