Tastypie - 允许未经授权的用户使用只读权限,同时允许授权的写入权限
问题描述:
我正在使用Tastypie 0.9.11,我希望未授权的用户在同一时间被授予对该API的只读权限,如果用户使用API密钥身份验证进行身份验证,该用户可以在这些相同模型上执行添加/更改/删除操作。Tastypie - 允许未经授权的用户使用只读权限,同时允许授权的写入权限
使用API密钥身份验证+ Django授权不满足要求1(未经身份验证的用户根本无法访问API)。 使用不认证不允许用户使用API密钥进行认证(不满足要求2)。
我敢打赌,有一个简单的方法来实现这种行为,请帮助。
非常感谢, 尤瓦·科恩
答
有你需要考虑两件事情。认证和授权。
首先,如果请求方法是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()
所以基本上你使用ApiKeyAuthentication
和DjangoAuthorization
方法只缺GET请求特殊处理。
感谢您的详细解决方案。它运作良好。我跳过了MyAuthorization,因为DjangoAuthorization已经允许所有的GET请求。 –
不客气:)我很高兴它的工作。 – kgr