请参考Django文档:编写身份验证后端 https://docs.djangoproject.com/en/1.7/topics/auth/customizing/#writing-an-authentication-backend,这可能就是您所追求的。它涵盖了正常登录和 REST API(例如令牌身份验证)的用例:
The authenticate method takes credentials as keyword arguments.
Most of the time, it’ll just look like this:
class MyBackend(object):
def authenticate(self, username=None, password=None):
# Check the username/password and return a User.
...
But it could also authenticate a token, like so:
class MyBackend(object):
def authenticate(self, token=None):
# Check the token and return a User.
...
Either way, authenticate should check the credentials it gets,
and it should return a User object that matches those credentials,
if the credentials are valid. If they’re not valid, it should return None.
一旦您编写了自定义身份验证后端,您只需在您的应用程序中更改默认身份验证后端即可。settings.py
像这样:
AUTHENTICATION_BACKENDS = ('project.path.to.MyBackend',)
Update
而不是覆盖默认值authenticate
行为,您可以在设置中包含两个后端,例如:
AUTHENTICATION_BACKENDS = ('project.path.to.MyBackend',
'django.contrib.auth.backends.ModelBackend',)
后端的顺序很重要,您可以阅读源代码并更好地理解默认情况authenticate
并且事物协同工作(在这里阅读 https://github.com/django/django/blob/master/django/contrib/auth/backends.py)
AFAIK 这是定制的首选方式authenticate
,因为有一天您可能会将默认后端更改为 RemoteUserBackend 或其他内容(例如来自 RestFramework),因此您可以按顺序将逻辑(MyBackend)放置在您的设置中,而无需担心破坏代码。
希望这可以帮助。