drf的权限扩充

drf框架为我们提供了基本的权限验证。主要包括三种验证

  1、AllowAny  所有用户

  2、IsAuthenticated  验证过的用户

  3、IsAdminUser  超级管理员

这些权限人员不一定满足项目的权限需求。那么如果我们想定义新的权限,需要继承BasePermission

#定义新的权限
class SVIPPermission(BasePermission):
    message = "必须是SVIP才能访问"

    def has_permission(self, request, view):
        if request.user.id != 1:
            return False
        return True

使用新的权限

#jwtapp/permisson

#
新权限的局部使用 class UserList(APIView): permission_classes = [SVIPPermission] # 接口中加权限 authentication_classes = [JSONWebTokenAuthentication] def get(self,request, *args, **kwargs): print(request.META.get('HTTP_AUTHORIZATION', None)) return Response({'name':'zhangsan'}) def post(self,request, *args, **kwargs): return Response({'name':'zhangsan'})
#全局使用
REST_FRAMEWORK = {
    'DEFAULT_AUTHENTICATION_CLASSES': (
            'rest_framework_jwt.authentication.JSONWebTokenAuthentication',
        'rest_framework.authentication.SessionAuthentication',
        'rest_framework.authentication.BasicAuthentication',
    ),
    'DEFAULT_PERMISSION_CLASSES': (
        'jwtapp.permisson.SVIPPermission',
     ),
}    

猜你喜欢

转载自www.cnblogs.com/ppzhang/p/12662573.html