Authorization for azure REST API call

Rakesh S 151 Reputation points
2020-07-17T06:06:45.693+00:00

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!!

Azure IoT Hub
Azure IoT Hub
An Azure service that enables bidirectional communication between internet of things (IoT) devices and applications.
1,197 questions
{count} votes

Accepted answer
  1. Rakesh S 151 Reputation points
    2020-07-31T05:22:59.7+00:00

    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".

    0 comments No comments

1 additional answer

Sort by: Most helpful
  1. 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.

    1 person found this answer helpful.

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.