diff --git a/rest_framework/authentication.py b/rest_framework/authentication.py index 3f3bd2227c..971d80983f 100644 --- a/rest_framework/authentication.py +++ b/rest_framework/authentication.py @@ -150,10 +150,10 @@ def dummy_get_response(request): # pragma: no cover class TokenAuthentication(BaseAuthentication): """ - Simple token based authentication. + Simple token-based authentication. Clients should authenticate by passing the token key in the "Authorization" - HTTP header, prepended with the string "Token ". For example: + HTTP header, prepended with the string "Token ". For example: Authorization: Token 401f7ac837da42b97f613d789819ff93537bee6a """ @@ -167,31 +167,19 @@ def get_model(self): from rest_framework.authtoken.models import Token return Token - """ - A custom token model may be used, but must have the following properties. - - * key -- The string identifying the token - * user -- The user to which the token belongs - """ - def authenticate(self, request): auth = get_authorization_header(request).split() - if not auth or auth[0].lower() != self.keyword.lower().encode(): + if len(auth) != 2 or auth[0].lower() != self.keyword.lower().encode(): return None - - if len(auth) == 1: - msg = _('Invalid token header. No credentials provided.') - raise exceptions.AuthenticationFailed(msg) - elif len(auth) > 2: - msg = _('Invalid token header. Token string should not contain spaces.') - raise exceptions.AuthenticationFailed(msg) - + + token = auth[1] try: - token = auth[1].decode() + token = token.decode() except UnicodeError: - msg = _('Invalid token header. Token string should not contain invalid characters.') - raise exceptions.AuthenticationFailed(msg) + raise exceptions.AuthenticationFailed( + _('Invalid token header. Token string should not contain invalid characters.') + ) return self.authenticate_credentials(token) @@ -205,7 +193,7 @@ def authenticate_credentials(self, key): if not token.user.is_active: raise exceptions.AuthenticationFailed(_('User inactive or deleted.')) - return (token.user, token) + return token.user, token def authenticate_header(self, request): return self.keyword