Tastypie : Authentication for GET and Anonymous for POST

后端 未结 2 1165
广开言路
广开言路 2021-02-14 07:21

I use Django/Tastypie to manage my user collection.

Is it possible to allow anonymous users to POST in the API (when creating a new user at some endpoint) and restrict a

2条回答
  •  谎友^
    谎友^ (楼主)
    2021-02-14 08:08

    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)
    

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

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

提交回复
热议问题