Django CORS cannot set cookie in HTTP

52 Views Asked by At

Premise

I wanna use Django sessionid feature to identify which user was sending request. Therefore I need the user to login first and expect the user will bring the sessionid in their request header cookie then.

What's wrong now

login/ response header shows: This attempt to set a cookie via a Set-Cookie header was blocked because it had the "Secure" attribute but was not received over a secure connection. I'd like to find a way NOT to use https since it's just not quite a big project so I don't want to make too much effort on configuring https environments. Not sure if I set CORS or use sessionid feature correctly either. enter image description here

Related environment and codes

I have a Django backend server in my local network

Django 4.2.7
django-cors-headers 4.3.0
ip: http://192.168.10.200:8000

and my frontend dev environment (vue2.x) is on my own laptop

ip: http://192.168.10.101:8888

my setting.py is like below

# settings.py

INSTALLED_APPS = [
    "django.contrib.admin",
    "django.contrib.auth",
    "django.contrib.contenttypes",
    "django.contrib.sessions",
    "django.contrib.messages",
    "django.contrib.staticfiles",
    "corsheaders",
]

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_CREDENTIALS = True
CORS_ORIGIN_ALLOW_ALL = True
SESSION_COOKIE_SAMESITE = "None"
SESSION_COOKIE_SECURE = False
SECURE_SSL_REDIRECT = False
SESSION_COOKIE_HTTPONLY = True
CORS_ALLOWED_ORIGINS = ["http://localhost", "http://127.0.0.1", "http://192.168.10.101"]

views.py
this function will do the set_cookie if successfully logged in.

# views.py
@require_http_methods(["POST"])
def login(request):
...
    user = auth.authenticate(username=username, password=password)

    if user:
        auth.login(request, user)
        ret = {
            "code": 200,
            "errmsg": "OK",
        }
        response = JsonResponse(ret)
        response.set_cookie("sessionid", request.session.session_key, secure=False, httponly=True, samesite="None")
        return response
...

0

There are 0 best solutions below