Django-rest-auth 使用 cookie 而不是 Authorization header

标签 django cookies django-rest-framework django-rest-auth django-rest-framework-jwt

我想使用 Django Rest Framework 作为后端来构建 SPA 应用程序。应用程序将使用 token 身份验证。

为了最大的安全性,我想将身份验证 token 存储在 httpOnly cookie 中,因此无法从 javascript 访问它。但是,由于无法从 javascript 访问 cookie,因此我无法设置“授权: token ...” header 。

所以,我的问题是,我可以让 DRF 身份验证系统(或 Django-Rest-Knox/Django-Rest-JWT)从 cookie 中读取身份验证 token ,而不是从“授权” header 中读取它吗?或者“授权” header 是在 DRF 中进行身份验证的唯一且正确的方法?

最佳答案

我会覆盖 TokenAuthentication 的身份验证方法,假设 token 在 auth_token cookies :

class TokenAuthSupportCookie(TokenAuthentication):
    """
    Extend the TokenAuthentication class to support cookie based authentication
    """
    def authenticate(self, request):
        # Check if 'auth_token' is in the request cookies.
        # Give precedence to 'Authorization' header.
        if 'auth_token' in request.COOKIES and \
                        'HTTP_AUTHORIZATION' not in request.META:
            return self.authenticate_credentials(
                request.COOKIES.get('auth_token').encode("utf-8")
            )
        return super().authenticate(request)

然后设置 django-rest-framework 以在设置中使用该类:
REST_FRAMEWORK = {
    # other settings...
    'DEFAULT_AUTHENTICATION_CLASSES': (
        '<path>.TokenAuthSupportCookie',
    ),
}

关于Django-rest-auth 使用 cookie 而不是 Authorization header ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47274670/

相关文章:

css - django 模板中的内联 CSS 文件

Django 1.8 迁移。在创建数据库后添加 DateTimeField。最佳实践?

cookies - 没有第三方 cookie 的跨域用户跟踪?

Django REST Serializer 为多个嵌套关系执行 N+1 个数据库调用,3 个级别

python - 为 Django/Python 3 配置 Azure

python - 如何在表单完成期间设置外键(python/django)

javascript - 双重提交 Cookie 和多个选项卡?

javascript - 如何将 $cookies 注入(inject) AngularJS 服务?

Django 信号 request_finished 获取用户实例

python - Django-Nginx 补丁请求 :405 Method \"METHOD_OTHER\" not allowed