Django-rest-auth use cookie instead of Authorization header
Asked Answered
X

1

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?

Xeres answered 13/11, 2017 at 22:33 Comment(0)
W
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',
    ),
}
Wallache answered 27/7, 2018 at 7:23 Comment(3)
Note: I had to remove the .encode("utf-8") part in order to use this approach from the command line when using curl.Analeptic
But how do you make Django return the cookie in the first place? We can’t set an HttpOnly cookie it JavaScript after all.Haihaida
@Haihaida You would set the cookie in the login view. Here is an example: https://mcmap.net/q/825593/-django-rest-knox-with-cookiesOsvaldooswal

© 2022 - 2024 — McMap. All rights reserved.