我想使用Django Rest Framework作为后端来构建SPA应用程序。应用程序将使用令牌身份验证。
为了获得最大的安全性,我希望将身份验证令牌存储在javascript cookie中,这样就不能从httpOnly访问它。但是,因为无法从javascript访问cookie,所以我无法设置“Authorization: Token ...”标题。
所以,我的问题是,我能否让DRF身份验证系统(或Django-Rest-Knox/Django-Rest-JWT)从cookie中读取身份验证令牌,而不是从"Authorization“头中读取它?或者"Authorization“头是在DRF中进行身份验证的唯一且正确的方式?
发布于 2018-07-27 15:23:14
假设令牌在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').encode("utf-8")
)
return super().authenticate(request)然后设置django-rest-framework以在设置中使用该类:
REST_FRAMEWORK = {
# other settings...
'DEFAULT_AUTHENTICATION_CLASSES': (
'<path>.TokenAuthSupportCookie',
),
}https://stackoverflow.com/questions/47274670
复制相似问题