Created
January 5, 2021 09:21
-
-
Save goatwu1993/1105108e71b6a138168a2e9d160b357d to your computer and use it in GitHub Desktop.
Django_Channels3_SimpleJWT_Auth_Middleware.py
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
"""General web socket middlewares | |
""" | |
from channels.auth import AuthMiddlewareStack | |
from channels.db import database_sync_to_async | |
from channels.middleware import BaseMiddleware | |
from django.contrib.auth.models import AnonymousUser | |
from rest_framework_simplejwt.authentication import JWTTokenUserAuthentication | |
from rest_framework_simplejwt.state import User | |
@database_sync_to_async | |
def get_user(validated_token): | |
try: | |
return JWTTokenUserAuthentication().get_user(validated_token=validated_token) | |
except User.DoesNotExist: | |
return AnonymousUser() | |
class JwtAuthMiddleware(BaseMiddleware): | |
def __init__(self, inner): | |
self.inner = inner | |
async def __call__(self, scope, receive, send): | |
query = dict((x.split("=") for x in scope["query_string"].decode().split("&"))) | |
validated_token = JWTTokenUserAuthentication().get_validated_token( | |
raw_token=query.get("token") | |
) | |
scope["user"] = await get_user(validated_token=validated_token) | |
return await super().__call__(scope, receive, send) | |
def JwtAuthMiddlewareStack(inner): | |
return JwtAuthMiddleware(AuthMiddlewareStack(inner)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment