Tastypie - 允许未经身份验证的用户使用只读权限,同时授予授权的写入权限

时间:2012-09-03 13:33:42

标签: django django-authentication tastypie

我正在使用Tastypie 0.9.11并且我希望允许未经身份验证的用户获得对API的只读权限,同时,如果用户使用API​​密钥身份验证进行身份验证,则该用户可以执行添加/更改/删除这些模型上的操作。

使用API​​密钥身份验证+ Django授权不满足要求1(未经身份验证的用户根本无法访问API)。 使用无身份验证不允许用户使用API​​密钥进行身份验证(不满足要求2)。

我打赌有一种简单的方法可以实现这种行为,请帮忙。

非常感谢, Yuval Cohen

1 个答案:

答案 0 :(得分:8)

您需要考虑两件事。身份验证和授权。

首先,如果请求方法是GET,则无论API密钥如何都需要对所有用户进行身份验证,因为所有其他方法都使用ApiKeyAuthentication。

现在,所有经过身份验证的用户都需要获得授权。在这里,您还需要确保始终允许GET请求。这样的事情应该让你开始:

from tastypie.resources import ModelResource
from tastypie.authentication import ApiKeyAuthentication
from tastypie.authorization import DjangoAuthorization

class MyAuthentication(ApiKeyAuthentication):
    """
    Authenticates everyone if the request is GET otherwise performs
    ApiKeyAuthentication.
    """

    def is_authenticated(self, request, **kwargs):
        if request.method == 'GET':
            return True
        return super(MyAuthentication, self).is_authenticated(request, **kwargs)

class MyAuthorization(DjangoAuthorization)
    """
    Authorizes every authenticated user to perform GET, for all others
    performs DjangoAuthorization.
    """

    def is_authorized(self, request, object=None):
        if request.method == 'GET':
            return True
        else:
            return super(MyAuthorization, self).is_authorized(request, object)

class MyResource(ModelResource):

    class Meta:
        authentication = MyAuthentication()
        authorization = MyAuthorization()

所以基本上你使用ApiKeyAuthenticationDjangoAuthorization的方法只对GET请求缺乏特殊处理。

相关问题