gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-03 14:40:54 26 4
gpt4 key购买 nike

我想使用 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/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com