Django не устанавливает файлы cookie после развертывания

Я создал приложение vue и DRF, которое прекрасно работает локально, оно устанавливает access, refresh и токен csrf в cookies при входе в систему и поэтому все маршруты isAuthenticated работают нормально.

Но я передал его человеку, который должен развернуть его на vps, и теперь он не устанавливает cookie при входе. Я могу войти, но поскольку cookie не установлен, при обновлении он выводит меня из системы, и все маршруты выдают ошибку 401.

Вот мои настройки django, убираем secret_key здесь:

Это мой login_view:

from django.middleware import csrf
from rest_framework.views import APIView
from rest_framework.response import Response
from django.contrib.auth import authenticate
from rest_framework import status
from api.util import (set_access_cookies, set_refresh_cookies, get_tokens_for_user, combine_role_permissions,
                      extract_patient_role)
from api.serializers import UserSerializer, RoleSerializer
from django.utils import timezone
from api.models import User
from rest_framework_api_key.permissions import HasAPIKey
from rest_framework.permissions import AllowAny


class LoginView(APIView):
    authentication_classes = ()
    permission_classes = (HasAPIKey,)
    # permission_classes = (AllowAny,)

    def post(self, request):
        try:
            data = request.data
            response = Response()
            username = data.get('username', None)
            password = data.get('password', None)
            try:
                User.objects.get(email = username)
            except User.DoesNotExist:
                return Response({"msg": "User Credentails don't exist ! "}, status=status.HTTP_400_BAD_REQUEST)
            user = authenticate(username=username, password=password)
            if user.is_approved:
                if user is not None:
                    role, roles = extract_patient_role(user.roles.all())
                    permissions = combine_role_permissions(roles)
                    data = get_tokens_for_user(user, is_patient=False)
                    set_access_cookies(response, data['access'])
                    set_refresh_cookies(response, data['refresh'])
                    csrf.get_token(request)
                    data = UserSerializer(user, context={'request': request}).data
                    data['roles'] = RoleSerializer(roles, many=True).data
                    data['permissions'] = permissions
                    response.status_code = status.HTTP_200_OK
                    response.data = {"msg": "Login successfully", "user": data}
                    user.last_login = timezone.now()
                    user.save()
                    return response
                else:
                    return Response({"msg": "Invalid credentials"}, status=status.HTTP_404_NOT_FOUND)
            else:
                return Response({"msg": "Please verify account to log in"}, status=status.HTTP_400_BAD_REQUEST)
        except Exception as e:
            print(e)
            return Response({"msg": "Unable to Login"}, status=status.HTTP_400_BAD_REQUEST)

Это экземпляр axios для входа в систему:

import Vue from "vue";

import axios from "axios";

function getCookie(name) {
  var cookieValue = null;
  if (document.cookie && document.cookie !== "") {
    var cookies = document.cookie.split(";");
    for (var i = 0; i < cookies.length; i++) {
      var cookie = cookies[i].trim();
      if (cookie.substring(0, name.length + 1) === name + "=") {
        cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
        break;
      }
    }
  }
  return cookieValue;
}

const axiosIns2 = axios.create({
  baseURL: process.env.VUE_APP_API,
  withCredentials: true,
  xsrfCookieName: "csrftoken",
  xsrfHeaderName: "X-CSRFTOKEN",
  headers: {
    "X-CSRFTOKEN": getCookie("csrftoken"),
    Authorization: "Api-Key " + process.env.VUE_APP_KEY,
  },
});

Vue.prototype.$http = axiosIns2;

export default axiosIns2;

А это экземпляр axios для других аутентифицированных запросов:

import Vue from "vue";

import axios from "axios";

function getCookie(name) {
  var cookieValue = null;
  if (document.cookie && document.cookie !== "") {
    var cookies = document.cookie.split(";");
    for (var i = 0; i < cookies.length; i++) {
      var cookie = cookies[i].trim();
      if (cookie.substring(0, name.length + 1) === name + "=") {
        cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
        break;
      }
    }
  }
  return cookieValue;
}

const axiosIns = axios.create({
  baseURL: process.env.VUE_APP_API,
  withCredentials: true,
  xsrfCookieName: "csrftoken",
  xsrfHeaderName: "X-CSRFTOKEN",
  headers: {
    "X-CSRFTOKEN": getCookie("csrftoken"),
  },
});

const COOKIE_EXPIRED_MSG = "Token is invalid or expired";

axiosIns.interceptors.response.use(
  (response) => {
    return response;
  },
  async (error) => {
    let error_message = null;
    if (error.response.data.messages) {
      error_message = error.response.data.messages[0].message;
    }
    switch (error.response.status) {
      case 401:
        if (!error.config.retry && error_message === COOKIE_EXPIRED_MSG) {
          error.config.retry = true;
          // axiosIns.defaults.xsrfCookieName = "csrf_refresh_token";
          await axiosIns.post("/refresh");
          // axiosIns.defaults.xsrfCookieName = "csrf_access_token";
          return axiosIns(error.config);
        } else {
          throw new Error("Error");
        }
        break;
      default:
        break;
    }
    return Promise.reject(error);
  }
);

Vue.prototype.$http = axiosIns;

export default axiosIns;

Подробная информация об ОС VPS: Ubuntu 18.04.6

В настоящее время у меня нет доступа к VPS, я считаю, что эта проблема связана с настройками SIMPLE_JWT в settings.py.

Проект прекрасно работает с этими настройками локально, но на хостинге он не отправляет cookies при входе в систему. Тем не менее, он выдает 200 при входе.

Hosted Via: Nginx , Gunicorn

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