Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Consider channels-auth-token-middlewares #48

Open
johnthagen opened this issue Jun 14, 2023 · 0 comments
Open

Consider channels-auth-token-middlewares #48

johnthagen opened this issue Jun 14, 2023 · 0 comments

Comments

@johnthagen
Copy link

Thanks for the great tutorial! One thing that I had hoped could be improved is that a standard middleware could be used for token auth rather than having to implement this in each app.

channels-auth-token-middlewares recently added support for this in a standard way that can be reused, so I thought perhaps TestDriven IO might be interested in using that for the training tutorials.


channels-auth-token-middlewares provides a QueryStringSimpleJWTAuthTokenMiddleware to support token authentication out of the box when using Simple JWT with Django REST Framework.

Update INSTALLED_APPS:

INSTALLED_APPS = [
    # base django apps (django.contrib.auth is required)
    # other apps this one depends on (like rest_framework if it's necessary)
    'channels_auth_token_middlewares',
    # custom apps
]

Insert QueryStringSimpleJWTAuthTokenMiddleware into your ASGI application stack:

application = ProtocolTypeRouter(
    {
        "http": django_asgi_app,
        "websocket": AllowedHostsOriginValidator(
            QueryStringSimpleJWTAuthTokenMiddleware(
                URLRouter(...),
            ),
        ),
    }
)

Clients pass their JWT token into the token query parameter:

from websocket import create_connection

token = "EXAMPLE_TOKEN"
ws = create_connection(f"ws://127.0.0.1/ws/?token={token}")

The authenticated User (or AnonymousUser if the JWT is invalid) will be populated into the "user" key of the scope passed to the Consumer

class MyAsyncCommunicator(AsyncWebsocketConsumer):
    async def connect(self) -> None:
        user = self.scope["user"]
        # Validate user before accepting the Websocket Connection
        # For example:
        if not user.is_authenticated or user.is_anonymous:
            # Handle unauthorized.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant