Django REST API自定义令牌身份验证在将来的请求中无法识别令牌

时间:2015-09-30 20:24:09

标签: python django django-rest-framework

我目前正在使用我的Django应用程序和django-rest-framework遇到以下问题。

我根据以下内容编写了一个CustomAuthToken视图: Django rest framework: Obtain auth token using email instead username

account / 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 -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)我认为我做的一切正确,因为他们使用相同的请求标题,间距是正确的,我不认为有任何编码问题。

1 个答案:

答案 0 :(得分:4)

经过锻炼,我的WSGI配置中没有转发令牌,我更仔细地阅读了文档。

http://www.django-rest-framework.org/api-guide/authentication/#apache-mod_wsgi-specific-configuration

清楚地说明需要为WSGI配置WSGIPassAuthorization On