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