【问题标题】:Django Rest Framework additional authentication checksDjango Rest Framework 额外的身份验证检查
【发布时间】:2019-11-29 13:31:28
【问题描述】:

我正在使用 Django Rest Framework 开发应用程序。如何扩展对用户登录的身份验证检查?

例如,我需要检查登录用户的 is_active 和 created_at 属性,并根据它们的值允许或禁止登录,但前提是密码经过 Django 验证。

我了解 Django 和 Django Rest Framework 自定义身份验证。

https://docs.djangoproject.com/en/2.2/topics/auth/customizing/

https://www.django-rest-framework.org/api-guide/authentication/#custom-authentication

问题是,这需要我重新实现内置的身份验证检查。我想在此之上添加检查。

谢谢!

【问题讨论】:

    标签: django authentication django-rest-framework


    【解决方案1】:

    您可以扩展现有的身份验证后端,而无需重新实现所有逻辑,例如:

    from django.contrib.auth.backends import ModelBackend
    
    class MyModelBackend(ModelBackend):
        def authenticate(self, request, username=None, password=None):
            user = super().authenticate(request, username=None, password=None)
            if user and not user.is_active:
                return None
            return user
    

    不要忘记更新您的 settings.py 以使用您的自定义身份验证后端:

    AUTHENTICATION_BACKENDS = ['myapp.backends.MyModelBackend']
    

    【讨论】:

    • 谢谢!完美地工作。如果有人需要,您需要在 Django settings.py 中注册后端(我将它放在后端文件夹中): AUTHENTICATION_BACKENDS = ( 'myapp.backends.MyModelBackend', )
    猜你喜欢
    • 2019-01-01
    • 1970-01-01
    • 2013-05-03
    • 2021-09-09
    • 2015-11-12
    • 2015-12-26
    • 2020-04-10
    • 2015-06-01
    • 2017-01-25
    相关资源
    最近更新 更多