Warm tip: This article is reproduced from serverfault.com, please click

how to setup token for the first time login with axios?

发布于 2020-12-01 22:52:42

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?

Questioner
cikatomo
Viewed
22
buzatto 2020-12-02 09:00:42

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;
  });