AC-654 Add API support for token auth using X-Auth-Token header in addition to AUthorization header, fixes issue where API requests from the UI are picking up the basic auth from an API session.

This commit is contained in:
Chris Church
2013-11-19 23:22:30 -05:00
parent 52c0a93293
commit e4851c6e18
5 changed files with 75 additions and 26 deletions

View File

@@ -4,6 +4,7 @@
# Django REST Framework
from rest_framework import authentication
from rest_framework import exceptions
from rest_framework import HTTP_HEADER_ENCODING
# AWX
from awx.main.models import Job, AuthToken
@@ -16,9 +17,33 @@ class TokenAuthentication(authentication.TokenAuthentication):
model = AuthToken
def _get_x_auth_token_header(self, request):
auth = request.META.get('HTTP_X_AUTH_TOKEN', '')
if type(auth) == type(''):
# Work around django test client oddness
auth = auth.encode(HTTP_HEADER_ENCODING)
return auth
def authenticate(self, request):
self.request = request
return super(TokenAuthentication, self).authenticate(request)
# Prefer the custom X-Auth-Token header over the Authorization header,
# to handle cases where the browser submits saved Basic auth and
# overrides the UI's normal use of the Authorization header.
auth = self._get_x_auth_token_header(request).split()
if not auth or auth[0].lower() != 'token':
auth = authentication.get_authorization_header(request).split()
if not auth or auth[0].lower() != 'token':
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)
return self.authenticate_credentials(auth[1])
def authenticate_credentials(self, key):
try: