Django休息框架不认证自定义用户模型

时间:2015-11-11 18:11:17

标签: python django rest django-rest-framework django-custom-user

我有这个自定义用户模型:

class CustomUser(AbstractBaseUser,PermissionsMixin):
    email = models.CharField(max_length=255, unique=True)
    ....

此视图需要进行身份验证才能运行:

@authentication_classes((TokenAuthentication,))
@permission_classes((IsAuthenticated,))
def test_view(request):
    return HttpResponse("Allowed")

当我为此启动网址时,无论我是否在我的授权标头中提供凭据,它都将始终运行。我的猜测是,rest框架使用的是django的默认用户模型,因为request.user对象包含一个AnonymousUser实例。但是我检查了数据库,并且authtoken表引用了我的自定义用户表。

我认为这应该像我的代码一样简单,但我想我错过了一些东西。有什么想法吗?

编辑:以下是更多详情:

settings.py:

INSTALLED_APPS = (
    'myapps',
    ...
    'django.contrib.auth', #should this be enabled?
    ...
    'rest_framework.authtoken'
)
...
#I think this is unnecesary since i use per-view decorators, but...
REST_FRAMEWORK = {
    'DEFAULT_AUTHENTICATION_CLASSES': (
        'rest_framework.authentication.TokenAuthentication',
    )
}

AUTH_USER_MODEL = 'users.CustomUser'

urls.py:

urlpatterns = patterns('',
    ...
    url(r'^test', test_view, name='test'),
    ...
)

2 个答案:

答案 0 :(得分:1)

只需将@api_view(['GET'])装饰器添加到您的视图中,例如

from rest_framework.decorators import api_view

@api_view(['GET'])
@authentication_classes((TokenAuthentication,))
@permission_classes((IsAuthenticated,))
def test_view(request):
    return HttpResponse("Allowed")

答案 1 :(得分:0)

将以下内容添加到settings.py

如果您使用的是DRF令牌Auth:

INSTALLED_APPS = (
    ...
    'rest_framework.authtoken'
)

如果您正在使用JWT Auth:

REST_FRAMEWORK = {
     'DEFAULT_AUTHENTICATION_CLASSES': (
        'rest_framework_jwt.authentication.JSONWebTokenAuthentication',
    ),
    ...
}