[英]Django: How to override authenticate() method?
我使用自定义User
,并且有该用户的email_verified
字段。 我希望用户登录时被拒绝(如果此字段为false
。
我无法在views.py
执行此操作,因为用户可以从各种来源(Django站点,但也包括REST API)登录。 整个目的是避免为源代码中的N个符号编写N倍的逻辑。 我想重写models.py中的方法( login()
? authenticate()
?),使其仅执行一次。
我快速阅读了有关自定义身份验证的文档,但是没有找到我想要的东西。
感谢帮助。
请参考Django Doc: 编写身份验证后端 ,可能正是您所追求的。 它涵盖了您在常规登录和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',)
可以覆盖设置中的两个后端,而不是覆盖默认的authenticate
行为,例如:
AUTHENTICATION_BACKENDS = ('project.path.to.MyBackend',
'django.contrib.auth.backends.ModelBackend',)
后端的顺序很重要,您可以阅读源代码并更好地了解默认authenticate
和事物如何协同工作(请参阅此处 )
AFAIK这是自定义authenticate
的首选方法,因为您可能有一天可以将默认后端更改为RemoteUserBackend之类的内容(例如RestFramework中的内容),因此您只需按顺序在设置中放置逻辑(MyBackend),而无需担心破坏代码。
希望这可以帮助。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.