15

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?

user3601262
  • 651
  • 1
  • 7
  • 22

1 Answers1

11

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')
            )
        return super().authenticate(request)

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

REST_FRAMEWORK = {
    # other settings...
    'DEFAULT_AUTHENTICATION_CLASSES': (
        '<path>.TokenAuthSupportCookie',
    ),
}
rphlo
  • 661
  • 6
  • 9
  • Note: I had to remove the `.encode("utf-8")` part in order to use this approach from the command line when using curl. – summea Nov 13 '18 at 19:32
  • But how do you make Django return the cookie in the first place? We can’t set an HttpOnly cookie it JavaScript after all. – zerohedge Oct 11 '19 at 13:33
  • 1
    @zerohedge You would set the cookie in the login view. Here is an example: https://stackoverflow.com/a/56212049/2407209 – pymarco Jan 12 '20 at 21:51