Using Django DRF JWT Authentication with Django Channels

Using Django DRF JWT Authentication with Django Channels

This is for people who are already using django-rest-framework-simplejwt for Django REST Framework user authentication and want to use the same JWT token generated by django-rest-framework-simplejwt to authenticate users with Channels.

Sending the token over WebSocket from client to server

This step assumes that -

  • User is already authenticated to use Django DRF using JWT
  • A token is present on client side

We can only make use of querystring to send the token while opening the socket.

Create a new WebSocket using the endpoint -

// Retrieve your token on client side
let token = retrieveToken()
let endpoint = "ws://"
// Create new WebSocket
let socket = new WebSocket(endpoint + "?token=" + token)

Handling the token and authenticating the user

To authenticate the user in Channels using JWT, we will need to create a custom authentication middleware for Channels. Make a file yourproject/ -

from django.db import close_old_connections
from rest_framework_simplejwt.tokens import UntypedToken
from rest_framework_simplejwt.exceptions import InvalidToken, TokenError
from jwt import decode as jwt_decode
from django.conf import settings
from django.contrib.auth import get_user_model
from urllib.parse import parse_qs
class TokenAuthMiddleware:
    Custom token auth middleware
    def __init__(self, inner):
        # Store the ASGI application we were passed
        self.inner = inner
    def __call__(self, scope):
        # Close old database connections to prevent usage of timed out connections
        # Get the token
        token = parse_qs(scope["query_string"].decode("utf8"))["token"][0]
        # Try to authenticate the user
            # This will automatically validate the token and raise an error if token is invalid
        except (InvalidToken, TokenError) as e:
            # Token is invalid
            return None
            #  Then token is valid, decode it
            decoded_data = jwt_decode(token, settings.SECRET_KEY, algorithms=["HS256"])
            # Will return a dictionary like -
            # {
            #     "token_type": "access",
            #     "exp": 1568770772,
            #     "jti": "5c15e80d65b04c20ad34d77b6703251b",
            #     "user_id": 6
            # }
            # Get the user using ID
            user = get_user_model().objects.get(id=decoded_data["user_id"])
        # Return the inner application directly and let it run everything else
        return self.inner(dict(scope, user=user))

Now use this middleware in yourproject/ file -

from channels.auth import AuthMiddlewareStack
from channels.routing import ProtocolTypeRouter, URLRouter
import yourapp.routing
from .channelsmiddleware import TokenAuthMiddleware
application = ProtocolTypeRouter(
        # (http->django views is added by default)
        "websocket": TokenAuthMiddleware(

 Accessing the User in consumer

You can now access the user in yourapp/ like -

from channels.generic.websocket import AsyncWebsocketConsumer
class FooConsumer(AsyncWebsocketConsumer):
    async def websocket_connect(self, event):
        user = self.scope["user"]
        await self.accept()

Python FTW!

Originally published by Code Gabru at


Thanks for reading :heart: If you liked this post, share it with all of your programming buddies! Follow me on Facebook | Twitter

Learn More

☞ Complete Python Bootcamp: Go from zero to hero in Python 3

☞ Python and Django Full Stack Web Developer Bootcamp

☞ Python for Time Series Data Analysis

☞ Python Programming For Beginners From Scratch

☞ Beginner’s guide on Python: Learn python from scratch! (New)

☞ Python for Beginners: Complete Python Programming

☞ Django 2.1 & Python | The Ultimate Web Development Bootcamp

☞ Python eCommerce | Build a Django eCommerce Web Application

☞ Python Django Dev To Deployment

django python

Bootstrap 5 Complete Course with Examples

Bootstrap 5 Tutorial - Bootstrap 5 Crash Course for Beginners

Nest.JS Tutorial for Beginners

Hello Vue 3: A First Look at Vue 3 and the Composition API

Building a simple Applications with Vue 3

Deno Crash Course: Explore Deno and Create a full REST API with Deno

How to Build a Real-time Chat App with Deno and WebSockets

Convert HTML to Markdown Online

HTML entity encoder decoder Online

Python Django Tutorial | Django Course

🔥Intellipaat Django course: 👉This Python Django tutorial will help you learn what is django web development &...

Python Tricks Every Developer Should Know

In this tutorial, you’re going to learn a variety of Python tricks that you can use to write your Python code in a more readable and efficient way like a pro.

How to Remove all Duplicate Files on your Drive via Python

Today you're going to learn how to use Python programming in a way that can ultimately save a lot of space on your drive by removing all the duplicates. We gonna use Python OS remove( ) method to remove the duplicates on our drive. Well, that's simple you just call remove ( ) with a parameter of the name of the file you wanna remove done.

Basic Data Types in Python | Python Web Development For Beginners

In the programming world, Data types play an important role. Each Variable is stored in different data types and responsible for various functions. Python had two different objects, and They are mutable and immutable objects.

Main Pros and Cons of Django As A Web Framework for Python Developers

India's best Institute for Django Online Training Course & Certification. Django is a high-level Python Web framework that encourages rapid development and clean, pragmatic design.