36 lines
1.1 KiB
Markdown
36 lines
1.1 KiB
Markdown
# Device Registration and SAS Token Generation for Azure IoT Hub
|
||
|
||
## 🔧 Prerequisites
|
||
|
||
- Azure Subscription
|
||
- Azure IoT Hub created
|
||
- Azure CLI installed
|
||
- Device created in IoT Hub
|
||
|
||
---
|
||
|
||
## 1️⃣ Register a Device
|
||
|
||
```bash
|
||
az login
|
||
az account set --subscription "<your-subscription-id>"
|
||
|
||
az iot hub device-identity create --hub-name <your-hub-name> --device-id <your-device-id>
|
||
|
||
2️⃣ Get Device Connection String
|
||
az iot hub device-identity show-connection-string --hub-name <your-hub-name> --device-id <your-device-id>
|
||
|
||
3️⃣ Generate SAS Token
|
||
|
||
import base64, hmac, hashlib, time, urllib.parse
|
||
|
||
def generate_sas_token(uri, key, expiry=3600):
|
||
ttl = int(time.time()) + expiry
|
||
sign_key = f"{urllib.parse.quote_plus(uri)}\n{ttl}"
|
||
signature = base64.b64encode(hmac.new(base64.b64decode(key), sign_key.encode(), hashlib.sha256).digest())
|
||
return f"SharedAccessSignature sr={uri}&sig={urllib.parse.quote_plus(signature.decode())}&se={ttl}"
|
||
|
||
4️⃣ Use SAS Token in Firmware
|
||
Set the Authorization header in MQTT/TLS to the token string.
|
||
|