调用Azure IoT设备预配REST API登记设备时遇授权错误求助
I’ve run into this exact scenario when working with DPS’s REST API directly—let’s walk through how to replicate what the SDK does to get past that 401 and successfully register your device.
Here’s the breakdown of what’s happening:
DPS uses a "challenge-response" flow for device registration when the initial authorization token isn’t valid (or uses the wrong key). The SDK automatically handles this retry, but when calling the API directly, you need to implement this flow manually.
Step 1: Handle the initial 401 response
When you send your first enrollment request (POST to https://<your-dps-hostname>/enrollments/<enrollment-id>/register?api-version=2021-06-01), you’ll get a 401 response with:
- The error message
"Authorization required, resend request using supplied key" - A
keynameandauthenticationkeyin the response body (or sometimes response headers—check both)
You need to capture these two values immediately; they’re the key to generating a valid SAS token for the retry.
Step 2: Generate a new SAS token with the supplied key
The initial SAS token you used was likely signed with the wrong key (e.g., a group enrollment key instead of the device-specific derived key). Now, use the authenticationkey from the 401 response to create a new token following these rules:
- Signature base string: Format it as
sr=<your-dps-hostname>&se=<expiry-timestamp><your-dps-hostname>is your DPS instance’s full hostname (e.g.,my-dps.azure-devices-provisioning.net)<expiry-timestamp>is a Unix timestamp for when the token expires (use something like 30 minutes from now to avoid expiration issues)
- Sign the string: Use HMAC-SHA256 with the
authenticationkey(decode it from Base64 first), then encode the result back to Base64 and URL-encode it. - Build the full token: Combine all parts into the standard SAS format:
Don’t forget to include theSharedAccessSignature sr=<dps-hostname>&sig=<url-encoded-signature>&se=<expiry-timestamp>&skn=<keyname-from-401>sknparameter set to thekeynamefrom the 401 response—DPS needs this to map the token to the correct key.
Step 3: Retry the enrollment request
Take the new SAS token, set it as the value of the Authorization header in your request, and resend the same POST to the enrollment endpoint. This time, the request should succeed and return the device’s registration details.
Common pitfalls to avoid:
- Incorrect signature base string: Make sure there are no extra spaces, and the
srandseparameters are in the exact order shown. URL-encode any special characters in the hostname (though most DPS hostnames won’t need it). - Using the wrong key: The
authenticationkeyfrom the 401 is the only key you should use for the retry—don’t fall back to your original group or root key. - Expiry timestamp issues: Use a future timestamp (in seconds since epoch) that’s not too far out (DPS rejects tokens with very long expiry times).
内容的提问来源于stack exchange,提问作者krishnakumar

