Tastypie:GET 身份验证和 POST 匿名 [英] Tastypie : Authentication for GET and Anonymous for POST

查看:39
本文介绍了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.

这篇关于Tastypie:GET 身份验证和 POST 匿名的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆