06.drf(django)的权限
默认配置已经启用权限控制
- settings
'django.contrib.auth',
默认 migrate 会给每个模型赋予4个权限,如果 ORM 类不托管给django管理,而是直接在数据库中建表,模型的权限就不生效了?
一.如果需要经过登陆后才能访问,使用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
执行 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/