Django Multiple Authentication Backends Based On Status

一笑奈何 提交于 2019-11-30 17:33:55

问题


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 the User 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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!