Last active
August 31, 2021 16:14
-
-
Save manupatel007/0c0c3f9ded830684967ca550f2ff7bf2 to your computer and use it in GitHub Desktop.
Simple middleware to secure django channels 3.0 using Token authentication by simplejwt.
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 rest_framework_simplejwt.tokens import UntypedToken | |
from django.conf import settings | |
from jwt import decode as jwt_decode | |
from urllib.parse import parse_qs | |
from django.contrib.auth.models import User | |
from channels.db import database_sync_to_async | |
@database_sync_to_async | |
def get_user(user_id): | |
try: | |
return User.objects.get(id=user_id) | |
except User.DoesNotExist: | |
return AnonymousUser() | |
class TokenAuthMiddleware: | |
def __init__(self, app): | |
# Store the ASGI application we were passed | |
self.app = app | |
async def __call__(self, scope, receive, send): | |
token = parse_qs(scope["query_string"].decode("utf8"))["token"][0] | |
UntypedToken(token) | |
decoded_data = jwt_decode(token, settings.SECRET_KEY, algorithms=["HS256"]) | |
print(decoded_data) | |
scope['user'] = await get_user(int(decoded_data["user_id"])) | |
return await self.app(scope, receive, send) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment