In my React app I have
axios.defaults.headers.common["Authorization"] = `Token ${localStorage.getItem("token")}\`;
to send token with each request.
Now, I am trying to login for the first time to Django rest server, using djoser package, but I get this 401 response: {"detail":"Invalid token."}
I guess because there's no token yet.
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',
}
Should I do something on the frontend or backend, and what?
As the documentation points out to login you should reach the endpoint /auth/token/login/
and provide username
& password
to retrieve a new the token.
regarding the Authorization
you could do as:
const token = localStorage.getItem("token")
axios.defaults.headers.common["Authorization"] = token ? `Token ${token}` : null
or using iterceptors:
axios.interceptors.request.use(function (config) {
const token = localStorage.getItem("token")
config.headers.Authorization = token ? `Token ${token}` : null
return config;
});
the problem was that my code was sending '
Authorization: Token null
' instead of 'Authorization: null
'. The interceptor works better than default, because it sends token immediatelly for automatic request after login