我的文章How I could delete any video on YouTube 的靈感,並要檢查,如果在我的Django項目一切工作的安全,並在這裏結束了。
這是非常重要的問題! 答案非常好。
的Django Rest Framework
使得假象,一切工作正常,當一個人通過瀏覽的API觀點看它。
對象,驗證用戶擁有其中: ![enter image description here](https://i.stack.imgur.com/wbKy8.png)
對象,它驗證用戶確實不擁有: ![enter image description here](https://i.stack.imgur.com/URTWx.png)
隱藏DELETE鍵會讓你感覺,一切都很好。
您進行身份驗證,刪除按鈕隱藏。 酷!除非您使用CURL或其他工具進行測試,否則您會不知情,並注意到這個巨大的安全漏洞。
Django是有時過多魔....
實施例:
views.py
@authentication_classes((ExpiringTokenAuthentication, SessionAuthentication))
@permission_classes((IsOwnerOrReadOnly,))
class UserFavouritesSpotDetail(RetrieveUpdateDestroyAPIView):
model = UsersSpotsList
serializer_class = FavouritesSpotsListSerializer
def get_queryset(self):
queryset = UsersSpotsList.objects.filter(
role=1)
return queryset
def get_object(self):
queryset = self.get_queryset()
obj = get_object_or_404(
queryset,
pk=self.kwargs['pk'],
role=1)
self.check_object_permissions(self.request, obj)
return obj
通知書Shivansh提到的關鍵行:
self.check_object_permissions(self.request, obj)
當我錯過了這個漏洞能力是存在的。
permissions.py
from rest_framework import permissions
class IsOwnerOrReadOnly(permissions.BasePermission):
"""
Object-level permission to only allow owners of an object to edit it.
Assumes the model instance has an `user` attribute.
"""
def has_object_permission(self, request, view, obj):
# Read permissions are allowed to any request,
# so we'll always allow GET, HEAD or OPTIONS requests.
if request.method in permissions.SAFE_METHODS:
return True
return obj.user == request.user
TEST與http://www.getpostman.com/
它e.g提供的用戶不擁有令牌對象。
,如果一切正常,你應該看到「細節」:「您沒有權限執行此操作。「
![enter image description here](https://i.stack.imgur.com/XnNIg.png)
感謝您的回答! – andi 2015-04-04 22:23:54