Skip to content

Commit 0fb2426

Browse files
authored
Update secure-websocket-python.md
update python code
1 parent 90134e7 commit 0fb2426

File tree

1 file changed

+26
-41
lines changed

1 file changed

+26
-41
lines changed

articles/communication-services/how-tos/call-automation/includes/secure-websocket-python.md

Lines changed: 26 additions & 41 deletions
Original file line numberDiff line numberDiff line change
@@ -13,54 +13,39 @@ ms.author: kpunjabi
1313

1414
## Websocket code sample
1515

16-
This sample code demonstrates how to configure OIDC client to validate websocket payload using JWT
16+
This sample code demonstrates how to configure OIDC client to validate websocket payload using JWT. Install the following package:
17+
18+
`pip install cryptography`
1719

1820
```python
19-
from quart import Quart, websocket, abort, request import jwt from jwt import PyJWKClient, InvalidTokenError
20-
app = Quart(name)
21-
JWKS_URL = "https://acscallautomation.communication.azure.com/calling/keys" EXPECTED_ISSUER = "https://acscallautomation.communication.azure.com" EXPECTED_AUDIENCE = "ACS resource ID" # replace with actual audience
22-
async def validate_token(token: str): try: jwks_client = PyJWKClient(JWKS_URL) signing_key = jwks_client.get_signing_key_from_jwt(token).key
23-
decoded_token = jwt.decode(
21+
JWKS_URL = "https://acscallautomation.communication.azure.com/calling/keys"
22+
ISSUER = "https://acscallautomation.communication.azure.com"
23+
AUDIENCE = "ACS resource ID”
24+
@app.websocket('/ws') async def ws(): try: auth_header = websocket.headers.get("Authorization") if not auth_header or not auth_header.startswith("Bearer "): await websocket.close(1008) # Policy violation return
25+
token = auth_header.split()[1]
26+
27+
jwks_client = PyJWKClient(JWKS_URL)
28+
signing_key = jwks_client.get_signing_key_from_jwt(token)
29+
30+
decoded = jwt.decode(
2431
token,
25-
signing_key,
32+
signing_key.key,
2633
algorithms=["RS256"],
27-
audience=EXPECTED_AUDIENCE,
28-
issuer=EXPECTED_ISSUER,
34+
issuer=ISSUER,
35+
audience=AUDIENCE,
2936
)
3037

31-
return decoded_token # Could return claims if needed
32-
except InvalidTokenError:
33-
print("Token is invalid.")
34-
return None
35-
except Exception as e:
36-
print(f"Uncaught exception during token validation: {e}")
37-
return None
38-
39-
@app.websocket("/ws") async def ws(): auth_header = websocket.headers.get("Authorization")
40-
if not auth_header or not auth_header.startswith("Bearer "):
41-
await websocket.close(code=4401, reason="Missing or invalid Authorization header")
42-
return
43-
44-
token = auth_header.split(" ")[1]
38+
app.logger.info(f"Authenticated WebSocket connection with decoded JWT payload: {decoded}")
39+
await websocket.send("Connection authenticated.")
4540

46-
claims = await validate_token(token)
47-
if not claims:
48-
await websocket.close(code=4401, reason="Invalid token")
49-
return
50-
51-
correlation_id = websocket.headers.get("x-ms-call-correlation-id", "not provided")
52-
call_connection_id = websocket.headers.get("x-ms-call-connection-id", "not provided")
53-
print(f"Authenticated WebSocket - Correlation ID: {correlation_id}")
54-
print(f"Authenticated WebSocket - CallConnection ID: {call_connection_id}")
55-
56-
try:
5741
while True:
58-
message = await websocket.receive()
59-
print(f"Received: {message}")
60-
# TODO: process message
61-
except Exception as e:
62-
print(f"WebSocket closed: {e}")
63-
64-
if name == "main": app.run()
42+
data = await websocket.receive()
43+
# Process incoming data
6544

45+
except InvalidTokenError as e:
46+
app.logger.warning(f"Invalid token: {e}")
47+
await websocket.close(1008)
48+
except Exception as e:
49+
app.logger.error(f"Uncaught exception: {e}")
50+
await websocket.close(1011) # Internal error
6651
```

0 commit comments

Comments
 (0)