WookieeKushin
WookieeKushin

Reputation: 11

Change Header Key for rest_framework's TokenAuthorization

By default, rest_framework's TokenAuthentication uses the "Authorization" key in the header, and looks for the keyword "Token" when authenticating requests.

Authorization: Token [value]

How do I change it to use the "API-AUTH" key instead, and no keyword?

API-AUTH: [value]

Upvotes: 1

Views: 615

Answers (1)

annonymous
annonymous

Reputation: 816

You have to create a custom permission class that extends from TokenAuthentication and overrides the .authenticate() method.

The following codes are the modified code of the TokenAuthentication.authenticate() that accepts a request with API-AUTH as auth header name with the value of token with no keyword. You can find the original source code in the GitHub of Django rest framework here.

from django.contrib.auth.models import User
from django.utils.translation import gettext_lazy as _

from rest_framework import authentication
from rest_framework import exceptions
from rest_framework import HTTP_HEADER_ENCODING


class CustomTokenAuthentication(authentication.TokenAuthentication):
    def authenticate(self, request):
        auth = request.META.get('HTTP_API_AUTH', b'')
        if isinstance(auth, str):
            # Work around django test client oddness
            auth = auth.encode(HTTP_HEADER_ENCODING)

        auth = auth.split()
        if not auth:
            return None
        elif len(auth) > 1:
            msg = _('Invalid token header. Token string should not contain spaces.')
            raise exceptions.AuthenticationFailed(msg)

        try:
            token = auth[0].decode()
        except UnicodeError:
            msg = _('Invalid token header. Token string should not contain invalid characters.')
            raise exceptions.AuthenticationFailed(msg)

        return self.authenticate_credentials(token)

Then you can add CustomTokenAuthentication into settings.

REST_FRAMEWORK = {
    'DEFAULT_AUTHENTICATION_CLASSES': (
        ...  # other permission classes
        'path.to.CustomTokenAuthentication',
    ),
    ...  # other settings
}

Notes

  • Further readings about custom authentication can be found here.

Upvotes: 2

Related Questions