Django-rest-auth使用cookie代替Authorization头部。

15
我想使用Django Rest Framework作为后端构建单页应用程序。该应用程序将使用Token身份验证。
为了最大程度地提高安全性,我希望将身份验证令牌存储在httpOnly cookie中,以便无法从javascript访问。但是,由于cookie无法从javascript访问,因此我无法设置“Authorization:Token ...”标头。
因此,我的问题是,我能否使DRF身份验证系统(或Django-Rest-Knox / Django-Rest-JWT)从cookie读取身份验证令牌而不是从“Authorization”标头读取?还是“Authorization”标头是在DRF中进行身份验证的唯一和正确的方式?
1个回答

11

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

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')
            )
        return super().authenticate(request)

然后在设置中将django-rest-framework设置为使用该类:

REST_FRAMEWORK = {
    # other settings...
    'DEFAULT_AUTHENTICATION_CLASSES': (
        '<path>.TokenAuthSupportCookie',
    ),
}

注意:为了在使用curl时从命令行使用此方法,我必须删除.encode("utf-8")部分。 - summea
但是,你如何让Django首先返回Cookie呢?毕竟我们无法在JavaScript中设置HttpOnly cookie。 - zerohedge
1
@zerohedge 在登录视图中设置cookie。这里有一个示例:https://dev59.com/KLHma4cB1Zd3GeqPTPFS#56212049 - pymarco

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接