預設配置已經啟用權限控制
- settings
'django.contrib.auth',
預設 migrate 會給每個模型賦予4個權限,如果 ORM 類不托管給django管理,而是直接在資料庫中建表,模型的權限就不生效了
一.如果需要經過登陸後才能通路,使用 IsAuthenticated
IsAuthenticated
- 1.預設登陸,也可以通路drf的api
- 2.視圖裡加認證
from rest_framework.permissions import IsAuthenticated
permission_classes = (IsAuthenticated,)
- 3.設定全局認證方式
REST_FRAMEWORK = {
'DEFAULT_PERMISSION_CLASSES': (
'rest_framework.permissions.IsAuthenticated',
)
}
# 預設是
'DEFAULT_PERMISSION_CLASSES': (
'rest_framework.permissions.AllowAny',
)
二.隻允許模型安全方法 get/head/option DjangoModelPermissions
DjangoModelPermissions
執行 add delete 和 put 沒權限
{
"detail": "You do not have permission to perform this action."
}
[21/May/2020 14:20:18] "DELETE /idcs/1/ HTTP/1.1" 403 63
Forbidden: /idcs/2/
三.自定義權限,控制檢視的權限
- 1.permissions.py
class Permissions(DjangoModelPermissions):
def get_custom_perms(self, view, method):
if hasattr(view, "extra_perm_map"):
if isinstance(view.extra_perm_map, dict):
return view.extra_perm_map.get(method,[])
return []
def has_permission(self, request, view):
# Workaround to ensure DjangoModelPermissions are not applied
# to the root view when using DefaultRouter.
if getattr(view, '_ignore_model_permissions', False):
return True
if not request.user or (
not request.user.is_authenticated and self.authenticated_users_only):
return False
queryset = self._queryset(view)
perms = self.get_required_permissions(request.method, queryset.model)
perms.extend(self.get_custom_perms(view, request.method))
return request.user.has_perms(perms)
- 2.在需要增權重限的視圖增加額外權限
extra_perm_map = {
"GET": ['idcs.view_idc']
}
- 3.覆寫全局權限
'DEFAULT_PERMISSION_CLASSES': (
# 'rest_framework.permissions.DjangoModelPermissions',
'utils.permissions.Permissions',
)
- 4.如果沒授權
[21/May/2020 14:58:24] "GET / HTTP/1.1" 200 6511
Forbidden: /ProductModel/
https://www.w3cschool.cn/lxraw/lxraw-3meu35ov.html
https://www.django-rest-framework.org/api-guide/permissions/