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?
Most of the times I need authentication with any REST APIs defined through django-rest-framework I will use SessionAuthentication method. This method uses the session cookie (which is set through the normal Django login and logout views) to check out if there’s an authenticated user and get his username.
A common concept usually discussed with authentication is authorization. The authorization merely is granting access to specific features or services before or after authentication. In the Django framework, developers might mandate authentication before users can access some services.
Django REST framework OAuth The Django REST framework OAuth package provides both OAuth1 and OAuth2 support for REST framework. This package was previously included directly in REST framework but is now supported and maintained as a third party package.
The Django REST framework OAuthpackage provides both OAuth1 and OAuth2 support for REST framework. This package was previously included directly in the REST framework but is now supported and maintained as a third-party package. Installation & configuration Install the package using pip. pip install djangorestframework-oauth
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',
),
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With