Why am I getting a 403 Forbidden error when making a POST request to the login API in Vue.js?
I'm working on a Vue.js
application where users can log in through an API using the axios
library. However, when I send a POST request to the API endpoint, I'm getting a 403 Forbidden response.
Here's the Vue.js
code for the login request:
const response = await axios.post(
'https://apibackup.example.com/api/login/',
{
username: email.value,
password: password.value
},
{
headers: {
'Content-Type': 'application/json'
},
withCredentials: true,
withXSRFToken: true
}
)
And here's the login view from the Django backend:
def login_view(request):
if request.method == 'POST':
try:
data = json.loads(request.body)
form = LoginForm(data)
if form.is_valid():
username = form.cleaned_data['username']
password = form.cleaned_data['password']
user = authenticate(request, username=username, password=password)
if user is not None:
login(request, user)
# Logic for handling user types here...
else:
return JsonResponse({'status': 'error', 'message': 'Invalid username or password'}, status=401)
else:
return JsonResponse({'status': 'error', 'errors': form.errors}, status=400)
except json.JSONDecodeError:
return JsonResponse({'status': 'error', 'message': 'Invalid JSON data'}, status=400)
Here are the relevant settings from the Django
settings.py
:
CORS_ALLOW_CREDENTIALS = True
CORS_ALLOWED_ORIGINS = [
'https://example.com',
'http://localhost:5173',
# other domains...
]
CSRF_TRUSTED_ORIGINS = [
'https://example.com',
'http://localhost:5173',
# other domains...
]
CSRF_COOKIE_SAMESITE = 'None'
CSRF_COOKIE_SECURE = True
CSRF_COOKIE_DOMAIN = 'example.com'
Issue: When I try to log in, I get the following error in the browser console:
POST https://apibackup.example.com/api/login/ 403 (Forbidden)
This indicates that the request is forbidden, but I am not sure why. The server settings seem to allow the necessary origins and credentials, but the request still fails with a 403 status.
What I've tried:
Ensured that the CORS settings in settings.py are correctly set for the domain and include credentials. Checked that the withCredentials and withXSRFToken flags are correctly set in the axios request. Made sure the CSRF settings are configured correctly. Could someone please help me understand why I'm getting this 403 Forbidden error and how to resolve it?
Have you tried the solution from this post that also is related to Django? From what you described, it could be that you're missing the session cookies in your settings.py:
SESSION_COOKIE_SAMESITE = 'None'
SESSION_COOKIE_SECURE = True