django channels jwt auth

Solutions on MaxInterview for django channels jwt auth by the best coders in the world

showing results for - "django channels jwt auth"
Bastien
31 Sep 2016
1#Channels 3 auth is different from channels 2 you will have to create your own auth middleware for that start by creating a file channelsmiddleware.py
2#authmiddleware.py
3    """General web socket middlewares
4    """
5    
6    from channels.db import database_sync_to_async
7    from django.contrib.auth import get_user_model
8    from django.contrib.auth.models import AnonymousUser
9    from rest_framework_simplejwt.exceptions import InvalidToken, TokenError
10    from rest_framework_simplejwt.tokens import UntypedToken
11    from rest_framework_simplejwt.authentication import JWTTokenUserAuthentication
12    from rest_framework_simplejwt.state import User
13    from channels.middleware import BaseMiddleware
14    from channels.auth import AuthMiddlewareStack
15    from django.db import close_old_connections
16    from urllib.parse import parse_qs
17    from jwt import decode as jwt_decode
18    from django.conf import settings
19    @database_sync_to_async
20    def get_user(validated_token):
21        try:
22            user = get_user_model().objects.get(id=validated_token["user_id"])
23            # return get_user_model().objects.get(id=toke_id)
24            print(f"{user}")
25            return user
26       
27        except User.DoesNotExist:
28            return AnonymousUser()
29    
30    
31    
32    class JwtAuthMiddleware(BaseMiddleware):
33        def __init__(self, inner):
34            self.inner = inner
35    
36        async def __call__(self, scope, receive, send):
37           # Close old database connections to prevent usage of timed out connections
38            close_old_connections()
39    
40            # Get the token
41            token = parse_qs(scope["query_string"].decode("utf8"))["token"][0]
42    
43            # Try to authenticate the user
44            try:
45                # This will automatically validate the token and raise an error if token is invalid
46                UntypedToken(token)
47            except (InvalidToken, TokenError) as e:
48                # Token is invalid
49                print(e)
50                return None
51            else:
52                #  Then token is valid, decode it
53                decoded_data = jwt_decode(token, settings.SECRET_KEY, algorithms=["HS256"])
54                print(decoded_data)
55                # Will return a dictionary like -
56                # {
57                #     "token_type": "access",
58                #     "exp": 1568770772,
59                #     "jti": "5c15e80d65b04c20ad34d77b6703251b",
60                #     "user_id": 6
61                # }
62    
63                # Get the user using ID
64                scope["user"] = await get_user(validated_token=decoded_data)
65            return await super().__call__(scope, receive, send)
66    
67    
68    def JwtAuthMiddlewareStack(inner):
69        return JwtAuthMiddleware(AuthMiddlewareStack(inner))
70
71
72#you cant then import it into your consumer's routing.py or asgi.py file like this
73#asgi.py
74    """
75    ASGI config for config project.
76    It exposes the ASGI callable as a module-level variable named ``application``.
77    For more information on this file, see
78    https://docs.djangoproject.com/en/3.1/howto/deployment/asgi/
79    """
80    
81    import os
82    from channels.routing import ProtocolTypeRouter, URLRouter
83    from channels.auth import AuthMiddlewareStack
84    from django.core.asgi import get_asgi_application
85    from channels.security.websocket import AllowedHostsOriginValidator
86    from chat.consumers import ChatConsumer
87    from django.urls import path, re_path
88    from .channelsmiddleware import JwtAuthMiddlewareStack
89    
90    os.environ.setdefault("DJANGO_SETTINGS_MODULE", "config.settings.dev")
91    
92    application = ProtocolTypeRouter(
93        {
94            "http": get_asgi_application(),
95            "websocket": AllowedHostsOriginValidator(
96                JwtAuthMiddlewareStack(
97                    URLRouter(
98                        [
99                            #path(),your routes here 
100                        ]
101                    )
102                ),
103            ),
104        }
105    )
106