Tastypie:GET 身份验证和 POST 匿名

问题描述:

我使用 Django/Tastypie 来管理我的用户集合.

I use Django/Tastypie to manage my user collection.

是否可以允许匿名用户在 API 中发布(在某个端点创建新用户时)并限制经过身份验证的用户只能获取他们自己的用户,而不是所有用户?

Is it possible to allow anonymous users to POST in the API (when creating a new user at some endpoint) and restrict authenticated users to GET only their own user, but not all the users ?

感谢您的帮助.

我发现最简单的方法是对我正在使用的 Authentication 类进行子类化.当方法是 POST 时,只需覆盖 is_authenticated 方法以返回 True.

I found the easiest thing to do was subclass the Authentication class I'm using. Just override the is_authenticated method to return True when the method is POST.

class AnonymousPostAuthentication(BasicAuthentication):
    """ No auth on post / for user creation """

    def is_authenticated(self, request, **kwargs):
        """ If POST, don't check auth, otherwise fall back to parent """

        if request.method == "POST":
            return True
        else:
            return super(AnonymousPostAuthentication, self).is_authenticated(request, **kwargs)

我将验证放在 Validation 的子类中并覆盖 is_valid.

I put my validation in a subclass of Validation and override is_valid.

我以与上面 Sampson 相同的方式进行 GET 过滤.

I do the GET filtering the same way Sampson does it above.