Skip to content

Commit 52b665c

Browse files
Add note, update imports and refactor code
1 parent d7e2f43 commit 52b665c

File tree

2 files changed

+29
-28
lines changed

2 files changed

+29
-28
lines changed

articles/communication-services/tutorials/hmac-header-tutorial.md

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -18,6 +18,9 @@ zone_pivot_groups: acs-programming-languages-csharp-python
1818

1919
In this tutorial, you'll learn how to sign an HTTP request with an HMAC signature.
2020

21+
>[!NOTE]
22+
>We strongly encourage to use [Azure SDKs](https://github.com/Azure/azure-sdk). Approach described here is a fallback option for cases when Azure SDKs can't be used for any reason.
23+
2124
::: zone pivot="programming-language-csharp"
2225
[!INCLUDE [Sign an HTTP request with C#](./includes/hmac-header-csharp.md)]
2326
::: zone-end

articles/communication-services/tutorials/includes/hmac-header-python.md

Lines changed: 26 additions & 28 deletions
Original file line numberDiff line numberDiff line change
@@ -16,8 +16,8 @@ Before you get started, make sure to:
1616

1717
- Create an Azure account with an active subscription. For details, see [Create an account for free](https://azure.microsoft.com/free/?WT.mc_id=A261C142F).
1818
- Download and install [Python](https://www.python.org/).
19-
- Download and install [Visual Studio Code](https://code.visualstudio.com/).
20-
- Create an Azure Communication Services resource. For details, see [Create an Azure Communication Services resource](../../quickstarts/create-communication-resource.md). You'll need to record your **resourceEndpoint** and **resourceAccessKey** for this tutorial.
19+
- Download and install [Visual Studio Code](https://code.visualstudio.com/) or other IDE that supports Python.
20+
- Create an Azure Communication Services resource. For details, see [Create an Azure Communication Services resource](../../quickstarts/create-communication-resource.md). You'll need your **resource_endpoint_name** and **resource_endpoint_secret** for this tutorial.
2121

2222
## Sign an HTTP request with Python
2323

@@ -48,52 +48,50 @@ Open Visual Studio Code and create a new file named `SignHmacTutorial.py`. Save
4848
Update the `SignHmacTutorial.py` script with the following code to begin.
4949

5050
```python
51-
import json
52-
import requests
53-
import hashlib
54-
import base64
55-
import datetime
56-
import hmac
57-
from wsgiref.handlers import format_date_time
58-
from datetime import datetime
59-
from time import mktime
51+
from base64 import b64decode, b64encode
52+
from datetime import datetime, timezone
53+
from hashlib import sha256
54+
from hmac import digest
55+
from json import dumps
56+
from locale import LC_TIME, setlocale
57+
from requests import post
6058
```
6159

6260
## Prepare data for the request
6361

64-
For this example, we'll sign a request to create a new identity by using the Communication Services Authentication API (version `2021-03-07`).
62+
For this example, we'll sign a request to create a new identity by using the Communication Services Authentication API [(version `2021-03-07`)](https://github.com/Azure/azure-rest-api-specs/tree/main/specification/communication/data-plane/Identity/stable/2021-03-07).
6563

6664
Add the following code to the `SignHmacTutorial.py` script.
6765

66+
Replace `resource_endpoint_name` with your real resource endpoint name value. This value can be found in Overview section of your Azure Communication Services resource. It's the value of "Endpoint" after "https://".
67+
Replace `resource_endpoint_secret` with your real resource endpoint secret value. This value can be found in Keys section of your Azure Communication Services resource. It's the value of "Key" - either primary or secondary.
68+
6869
```python
69-
host = "resourceEndpointName"
70+
host = "resource_endpoint_name"
7071
resource_endpoint = f"https://{host}"
7172
path_and_query = "/identities?api-version=2021-03-07"
72-
secret = "resourceEndpointSecret"
73+
secret = "resource_endpoint_secret"
7374

7475
# Create a uri you are going to call.
7576
request_uri = f"{resource_endpoint}{path_and_query}"
7677

7778
# Endpoint identities?api-version=2021-03-07 accepts list of scopes as a body.
7879
scopes = ["chat"]
7980

80-
serialized_body = json.dumps(scopes)
81+
serialized_body = dumps(scopes)
8182
content = serialized_body.encode("utf-8")
8283
```
8384

84-
Replace `resourceEndpointName` with your real resource endpoint name value.
85-
Replace `resourceEndpointSecret` with your real resource endpoit secret value.
86-
8785
## Create a content hash
8886

8987
The content hash is a part of your HMAC signature. Use the following code to compute the content hash. You can add this method to `SignHmacTutorial.py` script.
9088

9189
```python
9290
def compute_content_hash(content):
93-
sha_256 = hashlib.sha256()
91+
sha_256 = sha256()
9492
sha_256.update(content)
9593
hashed_bytes = sha_256.digest()
96-
base64_encoded_bytes = base64.b64encode(hashed_bytes)
94+
base64_encoded_bytes = b64encode(hashed_bytes)
9795
content_hash = base64_encoded_bytes.decode('utf-8')
9896
return content_hash
9997
```
@@ -104,10 +102,10 @@ Use the following code to create a method for computing your HMAC signature.
104102

105103
```python
106104
def compute_signature(string_to_sign, secret):
107-
decoded_secret = base64.b64decode(secret)
105+
decoded_secret = b64decode(secret)
108106
encoded_string_to_sign = string_to_sign.encode('ascii')
109-
hashed_bytes = hmac.digest(decoded_secret, encoded_string_to_sign, digest=hashlib.sha256)
110-
encoded_signature = base64.b64encode(hashed_bytes)
107+
hashed_bytes = digest(decoded_secret, encoded_string_to_sign, digest=sha256)
108+
encoded_signature = b64encode(hashed_bytes)
111109
signature = encoded_signature.decode('utf-8')
112110
return signature
113111
```
@@ -128,9 +126,9 @@ Add the following code to the `SignHmacTutorial.py` script.
128126

129127
```python
130128
# Specify the 'x-ms-date' header as the current UTC timestamp according to the RFC1123 standard
131-
now = datetime.now()
132-
stamp = mktime(now.timetuple())
133-
date = format_date_time(stamp)
129+
utc_now = datetime.now(timezone.utc)
130+
setlocale(LC_TIME, 'en_US')
131+
date = utc_now.strftime('%a, %d %b %Y %H:%M:%S GMT')
134132
# Compute a content hash for the 'x-ms-content-sha256' header.
135133
content_hash = compute_content_hash(content)
136134

@@ -164,10 +162,10 @@ request_headers["Authorization"] = authorization_header
164162

165163
## Test the client
166164

167-
Call the endpoint by using `Requests`, and check the response.
165+
Call the endpoint and check the response.
168166

169167
```python
170-
response = requests.post(request_uri, data=content, headers=request_headers)
168+
response = post(request_uri, data=content, headers=request_headers)
171169
response_string = response.content.decode("utf-8")
172170
print(response_string)
173171
```

0 commit comments

Comments
 (0)