问题
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?
回答1:
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 theUser
object and the user is authenticated as usual. - If the credentials are not accepted by any backend, the authentication fails.
回答2:
As Django Runs all the backends one after another. What you can do is use the authenticate function in your views.py file.
For example you want check for staff user then
email = form.cleaned_data['email']
try:
name = StaffUser.objects.get(email=email)
except StaffUser.DoesNotExist:
return "Do whatever you want"
user = authenticate(username=form.cleaned_data['email'], password=form.cleaned_data['password'])
In this your autheticaton function will be called only when the user exists.
This is kind of rough idea use it as per your convenience.
来源:https://stackoverflow.com/questions/16116234/django-multiple-authentication-backends-based-on-status