async def test_missing_token(self): """Without token the connection is refused.""" application = JWTMiddleware(AsyncWebsocketConsumer()) comminucator = WebsocketCommunicator(application, "/") with self.assertRaises(ValueError): connected, _ = await comminucator.connect() self.assertFalse(connected) await comminucator.disconnect()
async def test_valid_token(self): """With a valid token the connection is accepted.""" token = AccessToken() token.set_exp(lifetime=timedelta(minutes=20)) application = JWTMiddleware(AsyncWebsocketConsumer()) comminucator = WebsocketCommunicator(application, f"/?jwt={token}") connected, _ = await comminucator.connect() self.assertTrue(connected) await comminucator.disconnect()
async def test_invalid_token(self): """With an invalid token the connection is refused.""" token = AccessToken() token.set_exp( from_time=timezone.now() - timedelta(minutes=30), lifetime=timedelta(minutes=1), ) application = JWTMiddleware(AsyncWebsocketConsumer()) comminucator = WebsocketCommunicator(application, f"/?jwt={token}") connected, _ = await comminucator.connect() self.assertFalse(connected) await comminucator.disconnect()
async def test_invalid_token(self): """With an invalid token the connection is refused.""" token = AccessToken() token.set_exp( from_time=timezone.now() - timedelta(minutes=30), lifetime=timedelta(minutes=1), ) application = JWTMiddleware(AsyncWebsocketConsumer()) communicator = WebsocketCommunicator(application, f"/?jwt={token}") connected, _ = await communicator.connect() self.assertTrue(connected) response = await communicator.receive_output() self.assertEqual(response["type"], "websocket.close") self.assertEqual(response["code"], 4003) await communicator.disconnect()
"""Module configuring the websocket application used in the asgi module.""" from channels.routing import URLRouter from channels.security.websocket import AllowedHostsOriginValidator from marsha.websocket.middlewares import JWTMiddleware from marsha.websocket.routing import websocket_urlpatterns base_application = JWTMiddleware(URLRouter(websocket_urlpatterns)) websocket_application = AllowedHostsOriginValidator(base_application)
async def test_invalid_scope_type(self): """Only websocket scope type is accepted.""" middleware = JWTMiddleware(AsyncWebsocketConsumer()) with self.assertRaises(ValueError): await middleware({"type": "wrong-type"}, None, None)