websocket Django频道权限

zzlelutf  于 2023-03-08  发布在  Go
关注(0)|答案(1)|浏览(118)

Django Channels框架中有没有支持的方式来编写连接到特定消费者的自定义权限?
类似于DRF:

class MyConsumer(generics.APIView):
    permission_classes = [IsAuthenticated, MyCustomPermission]
    authentication_classes = [TokenAuthentication]
xfb7svmp

xfb7svmp1#

对于任何寻找解决方案的人,我想出了这个解决方案:
1.使用check_permissions方法创建Permissions类。

from channels.exceptions import DenyConnection

    class Permissions(object):
        permission_classes = []
    
        def check_permissions(self):
            try:
                for permission in self.permission_classes:
                    if permission(scope=self.scope).validate() != None:
                        raise DenyConnection
            except PermissionError:
                raise DenyConnection

1.创建一个BasePermission类。

class BasePermission(object):
    def __init__(self, scope, *args, **kwargs) -> None:
        self.scope = scope

    def has_permission(self, *args, **kwargs) -> bool:
        return True

    def validate(self, *args, **kwargs):
        try:
            if not self.has_permission(*args, **kwargs):
                return PermissionError
        except Exception:
            return RuntimeError
        return None

1.然后用您的自定义权限重写has_perm

class NotAnonymousUser(BasePermission):

    def has_permission(self, *args, **kwargs) -> bool:
        try:
            return not isinstance(self.scope["user"],AnonymousUser)
        except Exception:
            return False

1.最后继承Permissions类并调用check_permissions方法。

class MyConsumer(Permissions, JsonWebsocketConsumer):
    permission_classes = [NotAnonymousUser]

    def connect(self):
        self.check_permissions()
                   .
                   .

相关问题