简体   繁体   中英

Axios not storing Django session cookie

I have a Django REST Framework API backend for my Vue app. I'm trying to use Django sessions for anonymous users but either Django isn't sending or Axios can't read the session cookie.

A new session is being created by checking Session.objects.all().count()

I'm trying to store cart data using JWTAuthentication for authenticated users and SessionAuthentication for anonymous users.

# settings.py

CORS_ALLOW_CREDENTIALS = True
CORS_ORIGIN_WHITELIST = (
    'localhost:8080',
    '127.0.0.1:8080',
)

SESSION_COOKIE_HTTPONLY = False

I've tried toggling SESSION_COOKIE_HTTPONLY in settings.py but still not able to see the cookie.

When intercepting the response the CSRF cookie is sent but the session cookie isn't included.

import axios from 'axios'
import Cookie from 'js-cookie'

axios.defaults.xsrfCookieName = 'csrftoken'
axios.defaults.xsrfHeaderName = 'X-CSRFToken'
axios.defaults.withCredentials = true
axios.interceptors.response.use(response => {
    const sessionCookie = Cookie.get()
    console.log('Cookie', sessionCookie)
    return response
})

In my DRF API tests I can see that the session cookie is in the response.

Set-Cookie: sessionid=zgndujlppk4rnn6gymgg1czhv1u0rqfc; expires=Thu, 11 Apr 2019 11:27:32 GMT; HttpOnly; Max-Age=1209600; Path=/; SameSite=Lax

class Test(APITestCase):
    def test_get(self):
        response = self.client.get('/store/1/')
        print(response.cookies['sessionid']

The issue was I was visiting the site at the URL localhost:8080 but the cookie was being saved under 127.0.0.1 .

Changing the URL to 127.0.0.1:8080 solved the problem.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM