提问者:小点点

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


我目前在Django应用程序和Django rest框架中遇到以下问题。

我根据Django rest框架编写了一个CustomAuthToken视图:使用电子邮件而不是用户名获取auth令牌

帐户/视图.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:

    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-身份验证方案)我认为我做的一切都是正确的,因为他们使用相同的请求头,间距是正确的并且我认为没有任何编码问题。


共1个答案

匿名用户

在解决了令牌没有在我的WSGI配置中转发的问题后,我更加仔细地重新阅读了文档。

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

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