在 javascript 中获取 Django 站点的会话 ID

Get session ID for a django site in javascript

如何使用 javascript 获取最终存储在 cookie 中的 django 会话 ID?

我需要获取该 ID 的原因是我正在通过 REST API 执行所有操作,包括身份验证。因此,开发移动应用程序的人正在使用 ionic,他们想向 API 发出请求以获取该会话 ID - 然后在以后的请求中使用它。有什么建议吗?

默认情况下,Javascript 无法使用 Django cookie 作为 SESSION_COOKIE_HTTPONLY setting is set to True by default, for good reason. You can set this to False and then your cookie will be accessible, but then your site will be more vulnerable to XSS

嘿,我认为这种方法不是最好的方法,你的后端在这里有一个 XSS 攻击的门,我认为最好你可以使用令牌进行身份验证,即使是正常的 token.auth 很好在 django-rest-framework 文档 http://www.django-rest-framework.org/api-guide/authentication/ but i use a lot JWT JSONweb token auth so u dont compromise other data than token, username or other custom stuff like roles or something your app logic have, since ionic its angular JS you can take a look into http://frederiknakstad.com/2013/01/21/authentication-in-single-page-applications-with-angular-js/ 上进行了说明,了解如何在前端移动应用程序上管理身份验证过程。

继 codeadict 的回答之后:

您可以使用 JSON Web 令牌,但它们涉及的内容要多一些。最简单的解决方案是使用令牌身份验证,您可以按照此处的说明进行设置:

http://www.django-rest-framework.org/api-guide/authentication/#tokenauthentication

当您使用 Ionic(它在幕后使用 AngularJS)时,一个可能更好的解决方案是一个名为 django-rest-auth 的包,专为您正在做的事情而构建。

获取该设置的说明在此处http://django-rest-auth.readthedocs.org/en/latest/ and they have also released an AngularJS module here: https://github.com/Tivix/angular-django-registration-auth

不要忘记打开 HTTPS / SSL,因为在没有它的情况下使用令牌身份验证是非常不安全的。

上面链接的 angular 模块为您处理获取和存储这些令牌,然后您需要在向 api 发出的每个请求中包含访问令牌(通过 $http 或 $request或其他)