Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django Multiple Authentication Backends Based On Status

I was wondering how to tell Django which authentication backend to use based on if the user is marked as staff or if they are not.

Can this be done?

like image 328
icebox3d Avatar asked Mar 25 '23 06:03

icebox3d


1 Answers

Since the authentication backend is used by Django to get the user object, it is not known at the time we're calling the backend wether the user will be marked as staff or not.

Is is still possible to use different backends for staff and non-staff user, by chaining backends as explained in Specifying authentication backends. For example if your settings are:

 AUTHENTICATION_BACKEND = (
     'myapp.auth.StaffUserBackend',
     'django.contrib.auth.backends.ModelBackend',
 )

where myapp.auth.StaffUserBackend only recognizes staff users, this will happen when an user authenticates:

  • The credentials are checked against StaffUserBackend.
  • If the user is staff and the credentials are correct, StaffUserBackend returns the user object and we're done.
  • If the user is not staff, credentials are checked against ModelBackend.
  • If the credentials are valid for a standard user, ModelBackend returns the User object and the user is authenticated as usual.
  • If the credentials are not accepted by any backend, the authentication fails.
like image 174
Nicolas Cortot Avatar answered Apr 02 '23 09:04

Nicolas Cortot