Token authentication does not work in production on django rest framework

主宰稳场 提交于 2021-02-08 12:34:09

问题


I have this strange issue and I can't find why. I've build the API using django 1.7 and django rest framework and token auth for api authentication. All works fine on local host, but when I'm trying to call an API endpoint which requires authentication on production machine I'm getting 403 status code along with the following message: {"detail":"Authentication credentials were not provided."}. What I'm doing wrong?

I'm sending the token in the headers as per documentation. Here's how my settings file looks like:

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

回答1:


For me, the problem was, that Apache didn't forward the Authorization-Header to the WSGI-Process. Here's the fix:

Just add

WSGIPassAuthorization on

to your Apache (vhost) config.



来源:https://stackoverflow.com/questions/30151833/token-authentication-does-not-work-in-production-on-django-rest-framework

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!