1

I've developed an API with django rest framework, my frontend is built in vue js, so I have to use fetch to communicate with the API.

function apiService(endpoint, method, data) {
    const config = {
        method: method || 'GET',
        body: data !== undefined ? JSON.stringify(data) : null,
        headers: {
            'content-type': 'application/json',
            'X-CSRFToken': CSRF_TOKEN
        }
    };
    return fetch(endpoint, config)
           .then(data => getJson(data))
           .catch(err => err)
    };

I've noticed that this code works properly, but I have a doubt on the fact that, because I've added the authentication permission on the api, I would have to send a token in the request, because I'm not conneccting from a browser. So, how this token is send to the api, if I don't send it.

  • It will normally send a cookie that has a session-id, and Django thus will look if for that session id, there is a user that has logged in. – Willem Van Onsem Jul 22 '21 at 16:49
  • @WillemVanOnsem I type 'document.cookie' in the console and this is the output: "tabstyle=html-tab; _xsrf=2|d1f3c838|d65d796531602abc0a275dcdb1e0096d|1626274319; csrftoken=p3lY4bWKdgphgLyguZR0m9bB4iX57VtrotbzZZgQRbaIQSZ1v5oTJmNjjtz3rXA8", so there isn't a session id. – Nicolò Teseo Jul 22 '21 at 19:02
  • `document.cookies` does *not* contain the cookie for `sessionid`: https://stackoverflow.com/questions/39356004/document-cookie-is-not-returning-all-the-cookies this is used as security mechanism to prevent malicious JavaScript code from "stealing" the session id, and reuse it to make other requests. – Willem Van Onsem Jul 22 '21 at 19:10
  • I would advise to open the developer console of your browser, and read the header of the request you have made. – Willem Van Onsem Jul 22 '21 at 19:11
  • Ok, thank you so much. – Nicolò Teseo Jul 22 '21 at 19:16

1 Answers1

0

This is done with a cookie that stores a sessionid (you can change it by altering it with the SESSION_COOKIE_NAME setting [Django-doc]. This cookie contains an identifier to look up the session you have with the webserver. If you have logged in with that cookie, then Django will can look up with which user has been logged in.

This cookie is send with a HttpOnly flag (you can change this with the SESSION_COOKIE_HTTPONLY setting, although I strongly recommend not to do this), so that means that normally JavaScript can not inspect that cookie. This is a security measure to prevent other malicious JavaScript to read that cookie and for example, start to talk with the server.

You can inspect this cookie for example in the browser Web development tools: by inspecting the request you have made and look to the Cookie: section of the header of the request.

Willem Van Onsem
  • 443,496
  • 30
  • 428
  • 555