TokenAuthentication:无法进行身份验证

时间:2015-05-05 15:03:07

标签: django rest authentication

我正在尝试从Django rest框架实现TokenAuthentication。 我能从服务器获取令牌密钥,

$curl -d "username=admin&password=admin"  http://localhost:8000/api-token-auth/
{"token":"a571a596eab2e4063da4b9250a05b570ba8e9786"}

我无法使用任何api

curl -X GET http://localhost:8000/cart/ -H "Authorization: Token a571a596eab2e4063da4b9250a05b570ba8e9786"
{"detail":"Authentication credentials were not provided."}

我的设置文件,

INSTALLED_APPS = (
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'rest_framework',
    'rest_framework.authtoken',
    'myapp',
)
MIDDLEWARE_CLASSES = (
    'django.contrib.sessions.middleware.SessionMiddleware',
    'django.middleware.common.CommonMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'django.contrib.auth.middleware.SessionAuthenticationMiddleware',
    'django.contrib.messages.middleware.MessageMiddleware',
    'django.middleware.clickjacking.XFrameOptionsMiddleware',
)
#rest framework
REST_FRAMEWORK = {
    'DEFAULT_FILTER_BACKENDS': (
        'rest_framework.filters.DjangoFilterBackend',
    ),
    'DEFAULT_PERMISSION_CLASSES': (
        'rest_framework.permissions.IsAuthenticated',
        'rest_framework.permissions.DjangoObjectPermissions',
    ),
    'DEFAULT_AUTHENTICATION_CLASSES': (
        'rest_framework.authentication.BasicAuthentication',
        'rest_framework.authentication.SessionAuthentication',
    )
}

1 个答案:

答案 0 :(得分:1)

您缺少

中的TokenAuthentication后端
'DEFAULT_AUTHENTICATION_CLASSES': (
        'rest_framework.authentication.BasicAuthentication',
        'rest_framework.authentication.SessionAuthentication',
    )

只需添加rest_framework.authentication.TokenAuthentication行即可。请记住,顺序很重要,因为身份验证后端是按顺序测试的。