@@ -13,39 +13,48 @@ ms.author: kpunjabi
13
13
14
14
## Websocket code sample
15
15
16
- This sample code demonstrates how to configure OIDC client to validate websocket payload using JWT. Install the following package:
16
+ This sample demonstrates how to configure an OIDC-compliant client to validate WebSocket connection requests using JWT.
17
17
18
+ Make sure to install the required package:
18
19
` pip install cryptography `
19
20
20
21
``` python
21
22
JWKS_URL = " https://acscallautomation.communication.azure.com/calling/keys"
22
23
ISSUER = " https://acscallautomation.communication.azure.com"
23
24
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(
31
- token,
32
- signing_key.key,
33
- algorithms = [" RS256" ],
34
- issuer = ISSUER ,
35
- audience = AUDIENCE ,
36
- )
37
-
38
- app.logger.info(f " Authenticated WebSocket connection with decoded JWT payload: { decoded} " )
39
- await websocket.send(" Connection authenticated." )
40
-
41
- while True :
42
- data = await websocket.receive()
43
- # Process incoming data
44
-
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
25
+
26
+ @app.websocket (' /ws' )
27
+ async def ws ():
28
+ try :
29
+ auth_header = websocket.headers.get(" Authorization" )
30
+ if not auth_header or not auth_header.startswith(" Bearer " ):
31
+ await websocket.close(1008 ) # Policy violation
32
+ return
33
+
34
+ token = auth_header.split()[1 ]
35
+
36
+ jwks_client = PyJWKClient(JWKS_URL )
37
+ signing_key = jwks_client.get_signing_key_from_jwt(token)
38
+
39
+ decoded = jwt.decode(
40
+ token,
41
+ signing_key.key,
42
+ algorithms = [" RS256" ],
43
+ issuer = ISSUER ,
44
+ audience = AUDIENCE ,
45
+ )
46
+
47
+ app.logger.info(f " Authenticated WebSocket connection with decoded JWT payload: { decoded} " )
48
+ await websocket.send(" Connection authenticated." )
49
+
50
+ while True :
51
+ data = await websocket.receive()
52
+ # Process incoming data
53
+
54
+ except InvalidTokenError as e:
55
+ app.logger.warning(f " Invalid token: { e} " )
56
+ await websocket.close(1008 )
57
+ except Exception as e:
58
+ app.logger.error(f " Uncaught exception: { e} " )
59
+ await websocket.close(1011 ) # Internal error
51
60
```
0 commit comments