Django Authentication
Django Authentication
Django Authentication
Authentication
Authentication
Channels supports standard Django authentication out-of-the-box for HTTP and
WebSocket
consumers, and you can write your own middleware or handling code
if you want to support
a different authentication scheme (for example,
tokens in the URL).
Django authentication
The AuthMiddleware in Channels supports standard Django authentication,
where the user
details are stored in the session. It allows read-only access
to a user object in the scope .
application = ProtocolTypeRouter({
"websocket": AuthMiddlewareStack(
URLRouter([
re_path(r"^front(end)/$", consumers.AsyncChatConsumer.as_asgi()),
])
),
})
While you can wrap the middleware around each consumer individually,
it’s recommended
you wrap it around a higher-level application component,
like in this case the URLRouter .
Note that the AuthMiddleware will only work on protocols that provide
HTTP headers in their
scope - by default, this is HTTP and WebSocket.
self.user = self.scope["user"]
Custom Authentication
If you have a custom authentication scheme, you can write a custom middleware
to parse the
details and put a user object (or whatever other object you need)
into your scope.
Here’s a simple example of a middleware that just takes a user ID out of the
query string and
uses that:
@database_sync_to_async
def get_user(user_id):
try:
return User.objects.get(id=user_id)
except User.DoesNotExist:
return AnonymousUser()
class QueryAuthMiddleware:
"""
Custom middleware (insecure) that takes user IDs from the query string.
"""
self.app = app
# Look up user from query string (you should also do things like
# populated).
class ChatConsumer(AsyncWebsocketConsumer):
...
...
# save the session (if the session backend does not access the db you can use
`sync_to_async`)
await database_sync_to_async(self.scope["session"].save)()
class SyncChatConsumer(WebsocketConsumer):
...
...
async_to_sync(login)(self.scope, user)
self.scope["session"].save()
Note