I've implemented basic authentication in Django
(with Mongo DB
) and am a newbie in it. I'm trying to consume some web services I had made with it in iOS and android applications. Now, the Django
backend returns the desired response in Postman (REST client) but not in the iOS app (which handles basic auth requests through authentication challenges and works behind the scenes) so I wish to ensure if the Django
implementation is correct (so that I shift my focus to iOS side). In iOS, the service returns a 401
Unauthorized
status and an empty response. Also, the authentication challenges (that are called by the OS automatically) are not received. I had also tried with third party networking libraries which behaved similarly! All this leads me to believe there's something wrong with the Django
implementation. So how do I verify if a particular web-service (built using not just Django
) works according to the basic auth protocol? Tips and tricks please.
Here's the authentication code:
import base64
from tastypie.authentication import Authentication
from .backend import CustomMongoEngineBackend
class MongoBasicAuthentication(Authentication):
"""
Customizing basic authentication to make it compatible with mongo
"""
def is_authenticated(self, request, **kwargs):
"""
Checks a user's nasic auth credentials against the current Mongo Auth Backend.
"""
if not request.META.get('HTTP_AUTHORIZATION'):
return False
try:
(auth_type, data) = request.META.get('HTTP_AUTHORIZATION').split()
if auth_type.lower() != 'basic':
return False
user_pass = base64.b64decode(data)
except:
return False
bits = user_pass.split(':', 1)
if len(bits) != 2:
return False
backend = CustomMongoEngineBackend()
user = backend.authenticate(email=bits[0], password=bits[1])
if user:
request.user = user
else:
return False
return True
def get_identifier(self, request):
return request.META.get('REMOTE_USER', 'nouser')
If you see this response header:
WWW-Authenticate: Basic realm="protected-area"
Then basic auth is enabled.