Django-rest-auth use cookie instead of Authorization header

前端 未结 1 2016
孤城傲影
孤城傲影 2021-02-05 19:48

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 a

1条回答
  •  悲&欢浪女
    2021-02-05 20:40

    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': (
            '.TokenAuthSupportCookie',
        ),
    }
    

    0 讨论(0)
提交回复
热议问题