TokenAuthentication for rest api not working in production

Hi,

Guys i have built an api with dajngo rest framework. I am using TokenAuthentication Everything works fine in local computer development mode. But when I deploy my api to server the api authentication does not work. It allows me to browse the api without any restriciton.

INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'rest_framework',
    'memeapp',
    'stickerapp',
    'debug_toolbar',
    'rest_framework.authtoken',
]

# https://www.django-rest-framework.org/api-guide/renderers/#setting-the-renderers
# How to disable admin-style browsable interface of django-rest-framework?
# https://stackoverflow.com/questions/11898065/how-to-disable-admin-style-browsable-interface-of-django-rest-framework
REST_FRAMEWORK = {
    'DEFAULT_RENDERER_CLASSES': [
        'rest_framework.renderers.JSONRenderer',
        'rest_framework.renderers.BrowsableAPIRenderer',
    ],
    # how to perform token authentication
    # https://www.django-rest-framework.org/api-guide/authentication/#tokenauthentication
    # https://simpleisbetterthancomplex.com/tutorial/2018/11/22/how-to-implement-token-authentication-using-django-rest-framework.html
    'DEFAULT_AUTHENTICATION_CLASSES': [
        'rest_framework.authentication.TokenAuthentication',  # <-- And here
    ],
    # The default permission policy may be set globally, using the DEFAULT_PERMISSION_CLASSES setting.
    # https://www.django-rest-framework.org/api-guide/permissions/#setting-the-permission-policy
    'DEFAULT_PERMISSION_CLASSES': [
         'rest_framework.permissions.IsAuthenticated',
    ]
}

Hi,

Can you please share the code for one of your views which should be available only to those who are authenticated but which is not behaving as expected when you deploy your app.

Cheers,

Conor

Hello there!
I hope you solved it, but for future references

Note that if deploying to Apache using mod_wsgi, the authorization header is not passed through to a WSGI application by default, as it is assumed that authentication will be handled by Apache, rather than at an application level.

If you are deploying to Apache, and using any non-session based authentication, you will need to explicitly configure mod_wsgi to pass the required headers through to the application. This can be done by specifying the WSGIPassAuthorization directive in the appropriate context and setting it to 'On' like so:

WSGIPassAuthorization On

It is refereced in Django Rest Documentation.