【问题标题】:Django-rest-auth use cookie instead of Authorization headerDjango-rest-auth 使用 cookie 而不是 Authorization 标头
【发布时间】:2018-04-26 17:53:45
【问题描述】:

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

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

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

【问题讨论】:

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


    【解决方案1】:

    我会覆盖TokenAuthentication 的身份验证方法,假设令牌在auth_token cookie 中:

    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',
        ),
    }
    

    【讨论】:

    • 注意:我必须删除 .encode("utf-8") 部分,以便在使用 curl 时从命令行使用此方法。
    • 但是你如何让 Django 首先返回 cookie?毕竟我们不能在 JavaScript 中设置 HttpOnly cookie。
    • @zerohedge 您将在登录视图中设置 cookie。这是一个例子:stackoverflow.com/a/56212049/2407209
    猜你喜欢
    • 1970-01-01
    • 2020-10-14
    • 2016-08-10
    • 2017-09-05
    • 2017-05-25
    • 2021-01-17
    • 2021-02-21
    • 2013-02-13
    • 1970-01-01
    相关资源
    最近更新 更多