Case-insensitive username login in Django

Fri, Mar 20, 2009

Uncategorized

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.

,

24 Responses to “Case-insensitive username login in Django”

  1. Anthony Lewis Says:

    Thank you for this. This is exactly the solution I was looking for.

    Reply

  2. toivotuo Says:

    Thanks, very useful.

    Reply

  3. Stavros Korokithakis Says:

    This won’t use Django’s index on username and will do a seqscan of the database instead, which is very slow with many users. You should either create an index or lowercase all usernames upon creation and search for those.

    Reply

  4. Hosmakix Says:

    This isn’t good, because you can still register users with the “same” username, like “user” and “User”. Then, one of them won’t be able to log in.

    Reply

  5. Hosmakix Says:

    Ok guys, I’ve got a hack that seems to be working well. But please be seated while reading it, and refrain yourself from screaming :)

    http://bpaste.net/show/17766/

    Reply

  6. Hosmakix Says:

    Oh and I forgot, this piece of code goes in one of your models.py file. (Well, at least it works that way for me).

    Reply

  7. szubi Says:

    What a hell!
    Nice trick ;-)

    Reply

  8. Conchita Murri Says:

    Great Tips would try out for sure.

    Reply

  9. Azorys Says:

    Thank you very much. This is what I looking for.

    Reply

  10. Seth Livingston Says:

    Thank you for the simple solution.

    Is this any different for a custom user model? Is the 10th line the only one I need to modify?

    Reply

  11. dennisfuture's karaoke songs Says:

    Hello to all, how is everything, I think every one is getting more from this website, and your views are
    good in favor of new viewers.

    Reply

  12. uncle buck's Says:

    whoah this blog is magnificent i love reading your articles.
    Keep up the good work! You know, a lot of people are searching around for this information,
    you can aid them greatly.

    Reply

  13. streaming vk Says:

    I’m really enjoying the theme/design of your website. Do you ever run into any browser
    compatibility problems? A handful of my blog audience have complained
    about my blog not working correctly in Explorer but looks great in Opera.
    Do you have any tips to help fix this problem?

    Reply

  14. expeditions conquistador steam Says:

    Great post. I am going through some of these issues as well..

    Reply

  15. steam keys Says:

    After I initially commented I seem to have clicked the -Notify me when new
    comments are added- checkbox and from now on whenever a comment is added I get four emails with
    the exact same comment. Perhaps there is a means you
    are able to remove me from that service? Kudos!

    Reply

  16. running with rifles free Says:

    This article is in fact a good one it helps new internet people, who are wishing in favor of blogging.

    Reply

  17. undertale steam Says:

    Appreciating the dedication you put into your website and in depth information you
    provide. It’s great to come across a blog every once in a while that isn’t the same unwanted rehashed information.
    Great read! I’ve saved your site and I’m including your RSS
    feeds to my Google account.

    Reply

Trackbacks/Pingbacks

  1. Регистронезависимый логин в Django | Александр Горбач - 24. Jul, 2012

    [...] Теперь наши логины регистронезависимы! P.S. код взят с http://blog.shopfiber.com/?p=220 VK.Widgets.Like("vk_like", {type: [...]

Leave a Reply