Authenticating to a django backend from a vite frontend on a different subdomain hosted on self-hosted coolify instance
Hello I am trying to deploy two applications to a self hosted Coolify instance and I am unable to authenticate from my frontend. They are on different subdomains as you can see from the example below:
- Vite frontend (format): https://project.mydomain.com/#/login
- Django backend (format): https://api.mydomain.mydomain.com/
(Also one thing to mention is that I am using caddy as my reverse proxy in Coolify)
When I try to login from the frontend I get the following error:
Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at https://api.mydomain.mydomain.com/api/api-token-auth/. (Reason: header ‘access-control-allow-origin’ is not allowed according to header ‘Access-Control-Allow-Headers’ from CORS preflight response)
I have been reading about CORS for days and still cannot figure it out. I have configured my django backend with the following settings
installed
django-cors-headers
made these changes to my
settings.py
INSTALLED_APPS = [
# in project
'budget',
# installed Packages
'rest_framework',
'rest_framework.authtoken',
"crispy_forms",
"crispy_bootstrap5",
"corsheaders",
#
# ---------------
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
]
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',
]
CORS_ALLOW_METHODS = (
"DELETE",
"GET",
"OPTIONS",
"PATCH",
"POST",
"PUT",
)
CORS_ALLOWED_ORIGINS = [
'https://project.mydomain.com',
]
# CORS_ALLOW_ALL_ORIGINS = True
CORS_ALLOW_CREDENTIALS = True
CORS_ALLOW_HEADERS = [
'accept',
'accept-encoding',
'authorization',
'content-type',
'dnt',
'origin',
'user-agent',
'x-csrftoken',
'x-requested-with',
]
In the frontend when I make request:
const axiosInstance = axios.create({
baseURL: apiUrl,
headers: initialHeaders,
withCredentials: true, // This is important for sending cookies
});
const response = await axiosInstance.post<AuthResponse>('/api-token-auth/', {
username,
password,
},
{
withCredentials: true,
headers: {
'Access-Control-Allow-Origin': '*',
'Content-Type': 'application/json'
},
});
Ideally, I would like it if these two services were just under the same subdomain in Coolify but I am not good with reverse proxies.
If anyone can point me in the right direction that would be a lot of help. thanks!