Reputation: 275
I read this article for creating device in azure iot hub but i have problems in creating sas token which return me HTTP 401 Unauthorized
https://learn.microsoft.com/en-us/azure/iot-dps/how-to-control-access
This is my method of creating the sas token:
private static String SCOPE_ID = "0ne0032AAD2";
private static final String GLOBAL_ENDPOINT = "global.azure-devices-provisioning.net";
private static final String SYMMETRIC_KEY = "symmetric key from hub";
private static final String REGISTRATION_ID = "device1";
public static HttpClient httpClient;
private static int httpTimeoutInMilliseconds = 24000;**
public static String generateSasToken() throws Exception {
// Token will expire in one hour
var expiry = Instant.now().getEpochSecond() + 3600;
String stringToSign = URLEncoder.encode(GLOBAL_ENDPOINT, StandardCharsets.UTF_8) + "\n" + expiry;
byte[] decodedKey = Base64.getDecoder().decode(SYMMETRIC_KEY);
Mac sha256HMAC = Mac.getInstance("HmacSHA256");
SecretKeySpec secretKey = new SecretKeySpec(decodedKey, "HmacSHA256");
sha256HMAC.init(secretKey);
Base64.Encoder encoder = Base64.getEncoder();
String signature = new String(encoder.encode(
sha256HMAC.doFinal(stringToSign.getBytes(StandardCharsets.UTF_8))), StandardCharsets.UTF_8);
String token = "SharedAccessSignature sr=" + URLEncoder.encode(GLOBAL_ENDPOINT, StandardCharsets.UTF_8)
+ "&sig=" + URLEncoder.encode(signature, StandardCharsets.UTF_8.name()) + "&se=" + expiry + "&skn=provisioningserviceowner";
return token;
}
Upvotes: 0
Views: 137
Reputation: 8235
Have a look at my answer (Update-2) with a detail implementation (C#). Basically the following inputs are for generating a sas_token:
endpointAddressUri = $"https://global.azure-devices-provisioning.net/{scopeId}/registrations/{deviceId}/register?api-version=2019-03-31";
Update:
Note, that the pointed example has been implemented for Azure IoT Central configured by the following variables in the application settings:
In the case for registering the device(s) for Azure IoT Hub via the Azure Device Provisioning Service, we have to use the Enrollment Group, see the following:
the following screen snippet shows my example:
The deviceKey is computed from the above primary key of the DPS Enrollment Group (group1) and from the specific deviceId.
The response of the azure function where is handled a device registration is the following (in this example the deviceid=device10101):
and finally, the following picture shows a registered device in the Azure Iot Hub:
Upvotes: 1