首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Django-rest-auth使用cookie代替Authorization头

Django-rest-auth使用cookie代替Authorization头
EN

Stack Overflow用户
提问于 2017-11-14 06:33:49
回答 1查看 3K关注 0票数 13

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

为了获得最大的安全性,我希望将身份验证令牌存储在javascript cookie中,这样就不能从httpOnly访问它。但是,因为无法从javascript访问cookie,所以我无法设置“Authorization: Token ...”标题。

所以,我的问题是,我能否让DRF身份验证系统(或Django-Rest-Knox/Django-Rest-JWT)从cookie中读取身份验证令牌,而不是从"Authorization“头中读取它?或者"Authorization“头是在DRF中进行身份验证的唯一且正确的方式?

EN

回答 1

Stack Overflow用户

发布于 2018-07-27 15:23:14

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

代码语言:javascript
复制
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以在设置中使用该类:

代码语言:javascript
复制
REST_FRAMEWORK = {
    # other settings...
    'DEFAULT_AUTHENTICATION_CLASSES': (
        '<path>.TokenAuthSupportCookie',
    ),
}
票数 7
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/47274670

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档