【问题标题】:Determine which DRF auth class authenticated successfully first确定首先成功验证的 DRF 身份验证类
【发布时间】:2022-12-08 04:46:49
【问题描述】:

假设我有以下 Django Rest Framework 身份验证类顺序:

REST_FRAMEWORK = {
    "DEFAULT_AUTHENTICATION_CLASSES": [
        "rest_framework.authentication.TokenAuthentication",
        "rest_framework.authentication.SessionAuthentication",
        "MyCustomAuthClass",
    ],
    ...
}

根据docs

REST framework 将尝试对列表中的每个类进行身份验证,并将使用成功通过身份验证的第一个类的返回值设置 request.user 和 request.auth。

在我看来,我想知道哪个类成功通过了身份验证。

我的用例是我想针对特定端点以不同方式处理第三个身份验证类。我目前正在重新验证这似乎是不必要的并且性能不佳:

def get(self, request):
    if (
        not TokenAuthentication().authenticate()
        and not SessionAuthentication().authenticate()
        and MyCustomAuthClass().authenticate(request)
    ):
        # do this
    else:
        # do something else

有没有办法做到这一点,或者我的方法是最好的选择?

【问题讨论】:

    标签: django django-rest-framework


    【解决方案1】:

    您可以像这样注释您的身份验证类返回的用户:

    class MyCustomAuthClass(BaseAuthentication):
        def authenticate(self, request):
            # get your user for example by token:
            user = User.objects.get(token=request.META.get("HTTP_AUTHORIZATION"))
            user.is_authenticated_on_my_custom_class = True
            return (user, token)
    

    然后在你看来你可以这样做:

    if hasattr(request.user, "is_authenticated_on_my_custom_class") and request.user.is_authenticated_on_my_custom_class:
        # do something for `MyCustomAuthClass`
    

    【讨论】:

      【解决方案2】:
      isinstance(request.successful_authenticator, MyCustomAuthClass)
      

      【讨论】:

        猜你喜欢
        • 2018-04-21
        • 1970-01-01
        • 2011-02-01
        • 1970-01-01
        • 1970-01-01
        • 2015-12-16
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多