Django-rest-auth使用cookie代替Authorization标头 [英] Django-rest-auth use cookie instead of Authorization header

查看:177
本文介绍了Django-rest-auth使用cookie代替Authorization标头的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I want to build the SPA application using Django Rest Framework as a back-end. The application will use Token authentication.

为了获得最大的安全性,我想将身份验证令牌存储在httpOnly cookie内,因此无法通过javascript访问。但是,由于无法通过javascript访问Cookie,因此无法设置 Authorization:Token ...标头。

For maximum security, I want to store the authentication token inside of httpOnly cookie, so it will not be accessible from javascript. However, because the cookie is not accessible from the javascript, I am not able to set the 'Authorization: Token ...' header.

所以,我的问题是,我能否使DRF身份验证系统(或Django-Rest-Knox / Django-Rest-JWT)从cookie中读取身份验证令牌而不是从授权标题中读取它?还是授权标头是在DRF中进行身份验证的唯一正确方法?

So, my question is, can I make the DRF auth system (or Django-Rest-Knox/Django-Rest-JWT) to read the authentication token from the cookie instead of reading it from the "Authorization" header? Or the "Authorization" header is the only and correct way to authenticate in DRF?

推荐答案

我会覆盖 TokenAuthentication ,假设令牌位于 auth_token cookie中:

I would override the authenticate method of TokenAuthentication, assuming the token is in 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设置为在设置中使用该类:

Then set django-rest-framework to use that class in settings:

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

这篇关于Django-rest-auth使用cookie代替Authorization标头的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆