use*_*262 8 django cookies django-rest-framework django-rest-auth django-rest-framework-jwt
我想使用Django Rest Framework作为后端来构建SPA应用程序。该应用程序将使用令牌身份验证。
为了获得最大的安全性,我想将身份验证令牌存储在httpOnly cookie中,因此无法从javascript访问它。但是,由于无法从javascript访问cookie,因此无法设置“ Authorization:Token ...”标头。
因此,我的问题是,我可以使DRF身份验证系统(或Django-Rest-Knox / Django-Rest-JWT)从Cookie中读取身份验证令牌,而不是从“ Authorization”标头中读取身份验证令牌吗?还是“授权”标头是在DRF中进行身份验证的唯一正确方法?
TokenAuthentication
假设令牌在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)
Run Code Online (Sandbox Code Playgroud)
然后设置 django-rest-framework 以在设置中使用该类:
REST_FRAMEWORK = {
# other settings...
'DEFAULT_AUTHENTICATION_CLASSES': (
'<path>.TokenAuthSupportCookie',
),
}
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
806 次 |
最近记录: |