确定哪个DRF身份验证类首先成功通过身份验证



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

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

根据文件:

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

在我的视图中,我想知道哪个类成功通过了身份验证。

我的用例是,我想为特定的端点以不同的方式处理第三个auth类。我目前正在重新验证,这似乎是不必要的,也不具有性能:

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

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

您可以对身份验证类返回的用户进行如下注释:

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`
isinstance(request.successful_authenticator, MyCustomAuthClass)

最新更新