访问 request.user 时 django-rest-framework 中的身份验证循环

Authentication loop in django-rest-framework when accessing request.user

我在 django-rest-framework 3.0.3 中定义了一个自定义身份验证方案,如下所示:

from django.contrib.auth.models import AnonymousUser
from rest_framework import authentication


class CustomAuthentication(authentication.BaseAuthentication):
    def authenticate(self, request):
        print 'authenticate!', request.user
        return (AnonymousUser(), None)

当我使用 CustomAuthentication 时,我得到一个 "maximum recursion depth exceeded" 错误,这被打印在我的日志中:

authenticate! authenticate! authenticate! authenticate! authenticate! etc.

从我的打印语句中删除 request.user 修复了这个无限循环。我不应该在定义自定义身份验证方案时使用 request.user 吗?

如此 document 建议:

request.user typically returns an instance of django.contrib.auth.models.User, although the behavior depends on the authentication policy being used.

If the request is unauthenticated the default value of request.user is an instance of django.contrib.auth.models.AnonymousUser.

我认为当使用request.user时,它会检查请求是否有用户对象,并递归地不断调用您的自定义身份验证方法。您需要在函数中 return User 对象。