0

I have an angular login page that sends an Ajax request to my django server (listening on a separate port from the angular application), and I am able to log my user in but a session cookie is not getting returned in the response for the client to store in the angular app. Here is what my backend settings.py looks like the for authentication specific stuff:

MIDDLEWARE = [
'django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'corsheaders.middleware.CorsMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',]

# Here are the session specific settings
SESSION_ENGINE = 'django.contrib.sessions.backends.signed_cookies'
SESSION_COOKIE_HTTPONLY = True
SESSION_COOKIE_AGE = 1800 # The age of session cookies, in seconds
CORS_ORIGIN_ALLOW_ALL = True

And here is my login view function that is hooked up to my login path:

@csrf_exempt
@require_POST
def login_view(request: HttpRequest):
    payload = request.body.decode()
    body = json.loads(payload)
    username = body['username']
    password = body['password']
    user = authenticate(request, username=username, password=password)
    if user is not None:
        login(request, user)# Log the user in
        return HttpResponse('Success')
    else:
        return HttpResponseBadRequest()

I am trying to used cookie/ session based authentication so that if the user closes the page and relaunches it before the session time has expired, it will direct them back to the landing page, and for a specific input select field only certain options are supposed to be returned based on the user, and that would need to be handled via the session authentication. Is there something that is not correct in my settings file?

Jasonca1
  • 4,848
  • 6
  • 25
  • 42

1 Answers1

1

Try to set SESSION_COOKIE_SECURE and CSRF_COOKIE_SECURE to False, maybe because your request is insecure

Django CSRF Cookie Not Set

Linh
  • 418
  • 4
  • 9
  • Do you know of a way to have django pass a csrf token to my login page to prevent csrf forgery? – Jasonca1 Feb 05 '19 at 01:38
  • Try to force csrf with [this decorator](https://docs.djangoproject.com/en/2.1/ref/csrf/#django.views.decorators.csrf.ensure_csrf_cookie). Besides I would look into the reason behind setting the CSRF_COOKIE_HTTPONLY to True, which as described [here](https://docs.djangoproject.com/en/2.1/ref/settings/#csrf-cookie-httponly) force you to retrieve the csrftoken from a hidden input form value, else you could read it straight from the cookie. Both approach are described here: https://docs.djangoproject.com/en/2.1/ref/csrf/#ajax – Linh Feb 05 '19 at 12:19