Django Multiple Authentication Backend for one project, HOW?

Rai Muhammad Ehtisham picture Rai Muhammad Ehtisham · Jun 12, 2013 · Viewed 23.2k times · Source

Need serious help here.

I have an application written in django/python and I have to extend it and include some other solution as an "app" in this application. For example my app to be integrated is named "my_new_app" Now there is a backend authentication written for the main application and i cannot use it. I have a mysql db to query from and the main app uses cassendra and redis mostly. So my question is, is there any way i can use a separate authentication backend for the new app "my_new_app" and run the both in the same domain? Question may not be that clear, i'll clarify if asked.

Answer

janos picture janos · Jun 13, 2013

You can have multiple authentication backends. Just set the AUTHENTICATION_BACKENDS in settings.py of your Django project to list the backend implementations you want to use. For example I often use a combination of OpenID authentication and the standard Django authentication, like this in my settings.py:

AUTHENTICATION_BACKENDS = (
    'django.contrib.auth.backends.ModelBackend',
    'django_openid_auth.auth.OpenIDBackend',
    )

In this example Django will first try to authenticate using django.contrib.auth.backends.ModelBackend, which is the default backend of Django. If that fails, then it moves on to the next backend, django_openid_auth.auth.OpenIDBackend.

Note that your custom backends must be at a path visible by Django. In this example I have to add django_openid_auth to INSTALLED_APPS, otherwise Django won't be able to import it and use it as a backend.

Also read the relevant documentation, it's very nicely written, easy to understand: https://docs.djangoproject.com/en/dev/topics/auth/customizing/