The problem is that browsers do not support the transfer of jwt auth headers when updating websocket, so basically that. Some time ago I ran into this problem and came up with a solution for passing a token through the request parameters - note that this is absolutely unsafe without TLS , since you are authenticating in the URI. I no longer have access to the exact code, but here is the idea:
from channels.generic.websockets import JsonWebsocketConsumer from channels.handler import AsgiRequest from rest_framework_jwt.serializers import VerifyJSONWebTokenSerializer from jwt.exceptions import InvalidTokenError from rest_framework.exceptions import ValidationError class Consumer(JsonWebsocketConsumer): def connect(self, message, **kwargs):
Register a user using
channel_routing = [ ... route_class(Consumer, path=r'^my-ws-endpoint$'), ]
In the browser, you can establish a connection to the web server by passing the token as a request parameter to the website URI:
let token: string = 'my-token';
You can then extract the authentication verification code in a decorator like @channel_session_user_from_http and simply decorate your connection procedures or extract the code in mixin if you use class-based routes.
I would like to repeat, however, that this approach is completely unsafe without the use of encryption, so when creating a URI, you should start with https/wss .
Edit : here is a pretty nice DRF authentication solution , suitable for both functions and class-based functions. It takes almost the same approach as mine, creating the request object and passing it to the authenticator.
source share