I am using Django rest with Djoser package and in local everything works fine.
I login with username and password to token/login/
and get token in response, but on heroku I get details:invalid token
response, which means I cannot even get a token.
Some settings:
REST_FRAMEWORK = {
'DEFAULT_PAGINATION_CLASS': 'rest_framework.pagination.PageNumberPagination',
'PAGE_SIZE': 1000,
'DEFAULT_AUTHENTICATION_CLASSES': [
'rest_framework.authentication.TokenAuthentication',
'rest_framework.authentication.SessionAuthentication',
],
'DEFAULT_PERMISSION_CLASSES': [
'rest_framework.permissions.IsAuthenticated',
],
'DEFAULT_SCHEMA_CLASS': 'drf_spectacular.openapi.AutoSchema',
}
MIDDLEWARE = [
'corsheaders.middleware.CorsMiddleware',
'django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
]
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',
'sales',
'inventory',
'graphene_django',
'corsheaders',
'django_pivot',
'drf_spectacular',
'django_extensions',
'djoser',
]
urlpatterns = [
path('admin/', admin.site.urls),
path('login/', LoginView.as_view()), ## left from Session authentication
path('', include('sales.urls')),
path('inventory/', include('inventory.urls')),
path('graphql', csrf_exempt(GraphQLView.as_view(graphiql=True))),
path('', include('djoser.urls')),
path('', include('djoser.urls.authtoken')),
# swagger paths
path('api/schema/', SpectacularAPIView.as_view(), name='schema'),
path('api/schema/swagger-ui/',
SpectacularSwaggerView.as_view(url_name='schema'), name='swagger-ui'),
]
on the frontend:
axios.defaults.headers["Authorization"] = `Token ${localStorage.getItem("token")}`;
What could be the wrong?
The issue was on frontend.
Line
sends a request header
Authorization: Token null
which backend interprets as invalid token. Better header would beAuthorization: null
which works.So something like this:
Personally I have used interceptor: