我遇到了一个奇怪的问题,但是我找不到原因。我使用Django 1.7和Django Rest Framework以及令牌身份验证构建了API。在本地主机上一切正常,但是当我尝试调用需要身份验证的API端点时,在生产环境中我会收到403状态代码以及以下消息:{"detail": "未提供身份验证凭据。"}。我做错了什么?
根据文档,我将令牌作为标头发送。这是我的设置文件的样子:
INSTALLED APPLICATIONS = (
'......',
'rest_framework',
'rest_framework.authtoken',
'rest_framework_swagger',
'corsheaders',
'......')
MIDDLEWARE_CLASSES = (
'corsheaders.middleware.CorsMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.locale.LocaleMiddleware',
'django.contrib.admindocs.middleware.XViewMiddleware',
'django.middleware.common.CommonMiddleware',
'admin_reorder.middleware.ModelAdminReorder',
)
REST_FRAMEWORK = {
'DEFAULT_PERMISSION_CLASSES': [
'rest_framework.permissions.AllowAny'
],
'DEFAULT_AUTHENTICATION_CLASSES': (
'rest_framework.authentication.SessionAuthentication',
'rest_framework.authentication.TokenAuthentication',
),
'PAGINATE_BY_PARAM': 'page_size',
'DEFAULT_PAGINATION_CLASS': 'rest_framework.pagination.PageNumberPagination',
'DEFAULT_FILTER_BACKENDS': ('rest_framework.filters.DjangoFilterBackend',),
'VIEW_DESCRIPTION_FUNCTION': 'rest_framework_swagger.views.get_restructuredtext'
}
REST_SESSION_LOGIN = False
CORS_ORIGIN_ALLOW_ALL = True
CORS_REPLACE_HTTPS_REFERER = True
并在django.middleware.csrf.CsrfViewMiddleware之后列出corsheaders.middleware.CorsPostCsrfMiddleware (https://github.com/ottoyiu/django-cors-headers/)。 - Chris Berragan