Django-rest-auth use cookie instead of Authorization header

让人想犯罪 __ 提交于 2020-11-30 12:01:34

问题


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

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.

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?


回答1:


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)

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

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


来源:https://stackoverflow.com/questions/47274670/django-rest-auth-use-cookie-instead-of-authorization-header

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!