Django Simple JWT + Axios, always getting 401. How can I fix this?

I’m using Nuxt and a pinia store to store the token (the token is present in the store). I've created a plugin for Axios as follows:

import axios from "axios";

export default defineNuxtPlugin((NuxtApp) => {
  axios.defaults.baseURL = "http://127.0.0.1:8000/api/";
  axios.defaults.withCredentials = false;
  axios.defaults.proxyHeaders = false;
  if (process.client) {
    let token = window.localStorage.getItem("authTokens");
    if (token) {
      token = JSON.parse(token);
      console.log(token.access);
      axios.defaults.headers.common["Authorization"] = `Bearer ${token.access}`;
    }
  }
  return {
    provide: {
      axios: axios,
    },
  };
});

The endpoint in Django REST Framework is defined like this:

class CreateEvent(CreateAPIView):
    permission_classes = [IsAuthenticated]
    serializer_class = CreateEventSerializer

    def post(self, request, *args, **kwargs):
        data = request.data.copy()
        z = request.META.get('HTTP_AUTHORIZATION')
        data['creator'] = request.user
        print(request.user, '--------------------')
        data['types'] = get_type_by_int(request.data.get('type', None))
        serializer = self.get_serializer(data=data)
        if serializer.is_valid():
            serializer.save()
            return Response(serializer.data, status=status.HTTP_201_CREATED)
        return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)

The method I use to call this endpoint is as follows:

async sendEvent(): Promise<void> {
  try {
    const { $axios } = useNuxtApp();
    const response = await $axios.post("event/create/", {
      latitiude: this.latitiude,
      longitude: this.longitude,
      description: this.description,
      type: this.type,
    });
    console.log("Event sent:", response.data);
  } catch (error) {
    console.error("Error while sending event");
  }
}

No matter what I do, I keep receiving a 401 error with the message: Authentication credentials were not provided. However, the z = request.META.get('HTTP_AUTHORIZATION') line contains a value.

Here are my DRF settings:

SIMPLE_JWT = {
    "ACCESS_TOKEN_LIFETIME": timedelta(minutes=15),
    "REFRESH_TOKEN_LIFETIME": timedelta(days=1),
    "TOKEN_OBTAIN_SERIALIZER": "account.utils.MyTokenObtainPairSerializer",
}

REST_FRAMEWORK = {
    "DEFAULT_AUTHENTICATION_CLASSES": (
        "rest_framework_simplejwt.authentication.JWTAuthentication",
    )
}

INSTALLED_APPS = [
    ...
    "rest_framework",
    "rest_framework_simplejwt",
    "corsheaders",
    "drf_yasg",
    ...
]

What could be causing this issue, and how can I resolve it?

I’ve tried changing the token to use Bearer and without it, editing the endpoint, making requests to this address using Postman, and modifying the simple_jwt settings. I know the token is being sent because if I change its structure, even when the token is new, I receive the following error: { "detail": "Given token not valid for any token type", "code": "token_not_valid", "messages": [ { "token_class": "AccessToken", "token_type": "access", "message": "Token is invalid or expired" } ] }

Вернуться на верх