Last active
April 10, 2025 16:38
-
-
Save AliRn76/1fb99688315bedb2bf32fc4af0e50157 to your computer and use it in GitHub Desktop.
Token authorization middleware for Django Channels 3
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from django.contrib.auth.models import AnonymousUser | |
from rest_framework.authtoken.models import Token | |
from channels.db import database_sync_to_async | |
from channels.middleware import BaseMiddleware | |
from project.settings import SIMPLE_JWT, SECRET_KEY | |
@database_sync_to_async | |
def get_user(token_key): | |
# If you are using normal token based authentication | |
try: | |
token = Token.objects.get(key=token_key) | |
return token.user | |
except Token.DoesNotExist: | |
return AnonymousUser() | |
# If you are using jwt | |
try: | |
user_id: int = jwt.decode(token_key, SECRET_KEY, algorithms=[SIMPLE_JWT['ALGORITHM']]).get(SIMPLE_JWT['USER_ID_CLAIM']) | |
except jwt.exceptions.DecodeError: | |
return AnonymousUser() | |
except jwt.exceptions.ExpiredSignatureError: | |
return AnonymousUser() | |
try: | |
return AnonymousUser() if user_id is None else User.objects.get(id=user_id) | |
except User.DoesNotExist: | |
return AnonymousUser() | |
class TokenAuthMiddleware(BaseMiddleware): | |
def __init__(self, inner): | |
super().__init__(inner) | |
async def __call__(self, scope, receive, send): | |
try: | |
token_key = (dict((x.split('=') for x in scope['query_string'].decode().split("&")))).get('token', None) | |
except ValueError: | |
token_key = None | |
scope['user'] = AnonymousUser() if token_key is None else await get_user(token_key) | |
return await super().__call__(scope, receive, send) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Hi there! I add another jwt authentication base on token for django channel with header and query_params just click here