我目前在Django应用程序和Django rest框架中遇到以下问题。在
我根据以下内容编写了一个CustomAuthToken视图: Django rest framework: Obtain auth token using email instead username
帐户/视图.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)
我的主菜网址.py以下内容:
^{pr2}$我的习惯认证.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
从我的设置.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。我不太清楚是什么问题。我需要更改令牌身份验证的设置吗?我不这么认为。因为用户在数据库中设置正确,即使我使用从AbstractUser继承的自定义用户对象。{我认为所有的编码都是正确的。在
在解决了这个问题之后,在我的WSGI配置中没有转发令牌,我重新仔细阅读了文档。在
http://www.django-rest-framework.org/api-guide/authentication/#apache-mod_wsgi-specific-configuration
明确指出,
WSGIPassAuthorization On
需要为WSGI配置。在相关问题 更多 >
编程相关推荐