我目前遇到以下问题与我的Django应用程序和Django -rest-framework。
我已经写了一个CustomAuthToken视图如下:Django rest框架:用email代替username获取auth token
账户/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)
我的主url .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)
My custom 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
And taken from my 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
返回"拒绝访问"。
登录工作正常,我正在接收所述令牌。
但是,我不能访问我的Userview。我不太确定是什么问题。我需要更改TokenAuthentication的设置吗?我不这么想。因为在数据库中正确设置了用户,即使我使用从AbstractUser继承的自定义用户对象。从文档(http://www.django-rest-framework.org/api-guide/authentication/#setting-the-authentication-scheme)我认为我做的一切都正确,因为他们使用相同的请求头,间距是正确的,我不认为有任何编码问题。
在我的WSGI配置中没有转发Token之后,我更仔细地重新阅读了文档。
http://www.django-rest-framework.org/api-guide/authentication/apache-mod_wsgi-specific-configuration
明确说明需要为WSGI配置WSGIPassAuthorization On