Permissions

Permissions can be applied to AsyncAPIConsumer and its subclasses, such as GenericAsyncAPIConsumer.

This is done by setting the permission_classes = [TestPermission] property of the consumer.

from djangochannelsrestframework.consumers import AsyncAPIConsumer
from djangochannelsrestframework.permissions import IsAuthenticated

class RoomConsumer(AsyncAPIConsumer):
    permission_classes = [IsAuthenticated]

You can also combine permission classes using boolean operations: | & ! are the supported operations.

from djangochannelsrestframework.consumers import AsyncAPIConsumer
from djangochannelsrestframework.permissions import IsAuthenticated

class RoomConsumer(AsyncAPIConsumer):
    permission_classes = [
        MyCustomPermission | IsAuthenticated
    ]

In addition to subclassing BasePermission You can also use any rest_framework.permissions.BasePermission on a consumer, you may need to update your subclasses to handle the CONNECT method, as the has_permission method is called with a proxy request using a CONNECT method string.

class AllowAny[source]

Always allow

async has_permission(scope, consumer, action, **kwargs)[source]

Called on every websocket message sent before the corresponding action handler is called.

Parameters:
  • scope (Dict[str, Any])

  • consumer (AsyncConsumer)

  • action (str)

Return type:

bool

class BasePermission[source]

Base permission class

Notes

You should extend this class and override the has_permission method to create your own permission class. You can also over override`can_connect` to determine if a websocket connection should even be permitted.

async has_permission (scope, consumer, action, **kwargs)
async can_connect(scope, consumer, message=None)[source]

Called during connection to validate if a given client can establish a websocket connection.

By default, this returns True and permits all connections to be made.

Parameters:
  • scope (Dict[str, Any])

  • consumer (AsyncConsumer)

Return type:

bool

async has_permission(scope, consumer, action, **kwargs)[source]

Called on every websocket message sent before the corresponding action handler is called.

Parameters:
  • scope (Dict[str, Any])

  • consumer (AsyncConsumer)

  • action (str)

Return type:

bool

class IsAuthenticated[source]

Allow authenticated users

async has_permission(scope, consumer, action, **kwargs)[source]

Called on every websocket message sent before the corresponding action handler is called.

Parameters:
  • scope (Dict[str, Any])

  • consumer (AsyncConsumer)

  • action (str)

Return type:

bool