【问题标题】:Tastypie - Allow read-only perms for unauthenticated users while letting authorized write permissionsTastypie - 允许未经身份验证的用户的只读权限,同时允许授权的写入权限
【发布时间】:2012-08-28 06:05:20
【问题描述】:

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

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

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

非常感谢, 尤瓦尔·科恩

【问题讨论】:

    标签: django django-authentication tastypie


    【解决方案1】:

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

    首先,如果请求方法是 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 请求的特殊处理。

    【讨论】:

    • 感谢详细的解决方案。它运作良好。我跳过了 MyAuthorization,因为 DjangoAuthorization 一直都允许 GET 请求。
    猜你喜欢
    • 2015-12-26
    • 1970-01-01
    • 2019-11-20
    • 1970-01-01
    • 2014-03-01
    • 2013-11-25
    • 2018-01-15
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多