By default django’s authentication module (django.contrib.auth) does a case-sensitive username look up. This means that a user with username ‘farhan’ will not be able to login as ‘Farhan’. Obviously, this is not the standard behavior that users expect. There was a ticket filed, but, unfortunately, the team doesn’t have time to fix (understandably, it is not just about making the change, they also have to worry about backwards compatibility). So, let’s see how we can quickly create a new authentication backend that supports case-insensitive backend.
So, we are writing a new authentication backend class, as always, my goal is to only rewrite what I have to rewrite and in this case since most of the functionality is already implemented by django.contrib.auth.backends.ModelBackend (the default backend), we will be inheriting this class and overriding one function. Once we have the new backend, we will specify it in settings.AUTHENTICATION_BACKENDS and we will be done. One caution though, make sure your sign-up process accounts for this and does not allow users to pick two variations of the same username (Farhan vs. farhan).
The model is pretty simple.
from django.contrib.auth.backends import ModelBackend from django.contrib.auth.models import User class CaseInsensitiveModelBackend(ModelBackend): """ By default ModelBackend does case _sensitive_ username authentication, which isn't what is generally expected. This backend supports case insensitive username authentication. """ def authenticate(self, username=None, password=None): try: user = User.objects.get(username__iexact=username) if user.check_password(password): return user else: return None except User.DoesNotExist: return None
Once you have the model defined, edit your settings.py and specify “AUTHENTICATION_BACKENDS”.
AUTHENTICATION_BACKENDS = ('myproject.myapp.backends.CaseInsensitiveModelBackend',)
That’s all you need. Restart your server, or in case of ‘django-admin runserver’ it would have restarted automatically, and your application will now have case-insensitive logins.
For more details about writing authentication backends please see this section in the django documentation.