I am now able to access the rest apis, just that the approach i have used now, is by using Shared access key. The SAS keysare generated from azure CLI, using the command,"az iot hub generate-sas-token -n {hub-name}." This token will be used as a header under the key name, "Authorization".
Authorization for azure REST API call
Hi,
I'm trying to call the inbuilt azure API by bearer token generation. The bearer token is generated using "https://login.microsoftonline.com/{tenantID}/oauth2/token," and using this token, I'm trying to access the get device API from IoT Hub. The headers I'm providing for the REST API call are content-type and Authorization(with the bearer token). But it is returning an error message as below.
Message;:;ErrorCode:IotHubUnauthorized;3cc43d2f-def7-4a3e-a2ue-eb367467ab90 is not valid;
Can anyone please help me in solving this?
Thanks in advance!!
1 additional answer
Sort by: Most helpful
-
Sander van de Velde | MVP 32,736 Reputation points MVP
2020-07-23T18:33:21.837+00:00 Check out Control access to IoT Hub and especially Security token structure.
There you see how to create a security token for access to the IoT Hub Rest API.
With that token, you can access the IoT Hub Rest API. You only need the connection string of a Shared Access policy (with sufficient rights).
private static string DeployManifest(string iotHubName, string deviceId, string token)
{
using var client = new HttpClient();client.DefaultRequestHeaders.Add("Authorization", token);
var body = File.ReadAllText("deloyment.manifest.json");
var stringContent = new StringContent(body, Encoding.UTF8, "application/json");var restUriPost = $"https://{iotHubName}/devices/{deviceId}/applyConfigurationContent?api-version=2020-03-13";
using var resultPost = client.PostAsync(restUriPost, stringContent).Result;
return resultPost.StatusCode.ToString();
}Keep in mind that connection string is not intended for distribution outside the cloud.