Azure Storage: Authenticate with an Azure VM Managed Identity
See more Azure Cloud Storage Examples
Run on an Azure VM with a system-assigned or user-assigned managed identity. In storage.json supply account and optionally managed_client_id. Assign Storage Blob Data Reader (or a suitable data role) at the needed scope. The example obtains a Storage-audience token from IMDS and uses it for a Blob HEAD request. Do not send IMDS traffic through a proxy or make its destination user-controlled.
The token is saved to private qa_data/azure/storage-token.json with an expires_at timestamp for the related examples. Cache it until shortly before expiration, then repeat token acquisition. This flow does not use a refresh token. A 401 and a 403 need different investigation: token validity/audience versus data permissions or account policy. Allow time for RBAC changes to propagate.
Uses direct Chilkat.Rest requests and Azure public-cloud endpoints with verified HTTPS. REST requests select service version 2026-04-06. Create local input/output directories before running. Account-key examples read account and access_key string fields from private qa_data/azure/storage.json; do not embed secrets in distributed applications. Entra examples explain their own configuration. Keep credentials, bearer tokens, SAS URLs and diagnostic dumps private. Shared Key is supported only where allowed by account policy; Entra authentication is preferred where available.
Transport success and HTTP status are checked separately. Writes are not automatically replayed after an uncertain response. IDs, ETags, continuation markers and file sizes are strings; counters and explicitly bounded offsets use int. No webhook or web server is required.
Chilkat Unicode C++ Downloads
#include <CkStringBuilderW.h>
#include <CkJsonObjectW.h>
#include <CkRestW.h>
#include <CkDateTimeW.h>
#include <CkSocketW.h>
#include <CkXmlW.h>
void ChilkatSample(void)
{
bool success = false;
// StringBuilder compares text by value in every generated language.
CkStringBuilderW textCompare;
// Assumes Chilkat is unlocked. See Global Unlock Sample.
success = false;
CkJsonObjectW config;
config.put_Strict(true);
success = config.LoadFile(L"qa_data/azure/storage.json");
if (success != true) {
wprintf(L"Could not load private Azure configuration.\n");
return;
}
textCompare.Clear();
textCompare.SetString(config.stringOf(L"account"));
bool sameText1 = textCompare.ContentsEqual(L"",true);
if ((config.JsonTypeOf(L"account") != 1) || (sameText1 == true)) {
wprintf(L"Supply the storage account name.\n");
return;
}
CkRestW identity;
identity.put_ConnectTimeoutMs(20000);
identity.put_IdleTimeoutMs(60000);
CkDateTimeW expires;
success = expires.SetFromCurrentSystemTime();
if (success != true) {
wprintf(L"Could not prepare the request.\n");
return;
}
// Azure VM IMDS only: fixed link-local endpoint, direct connection, no proxy.
// App Service, Functions and Azure Arc have different identity endpoints.
success = identity.Connect(L"169.254.169.254",80,false,false);
if (success != true) {
wprintf(L"IMDS is available only on an eligible Azure VM.\n");
return;
}
success = identity.AddHeader(L"Metadata",L"true");
if (success != true) {
wprintf(L"Could not prepare the request.\n");
return;
}
success = identity.AddQueryParam(L"api-version",L"2018-02-01");
if (success != true) {
wprintf(L"Could not prepare the request.\n");
return;
}
success = identity.AddQueryParam(L"resource",L"https://storage.azure.com/");
if (success != true) {
wprintf(L"Could not prepare the request.\n");
return;
}
// Optional user-assigned identity. Omit for the VM's system-assigned identity.
if (config.HasMember(L"managed_client_id") == true) {
textCompare.Clear();
textCompare.SetString(config.stringOf(L"managed_client_id"));
bool sameText2 = textCompare.ContentsEqual(L"",true);
if ((config.JsonTypeOf(L"managed_client_id") != 1) || (sameText2 == true)) {
wprintf(L"Invalid managed_client_id.\n");
return;
}
success = identity.AddQueryParam(L"client_id",config.stringOf(L"managed_client_id"));
if (success != true) {
wprintf(L"Could not prepare the request.\n");
return;
}
}
const wchar_t *tokenText = identity.fullRequestNoBody(L"GET",L"/metadata/identity/oauth2/token");
if (identity.get_LastMethodSuccess() != true) {
wprintf(L"Token request did not complete; inspect diagnostics privately.\n");
return;
}
if (identity.get_ResponseStatusCode() != 200) {
wprintf(L"Token request failed; inspect the status privately, never print the response token.\n");
return;
}
CkJsonObjectW token;
token.put_Strict(true);
success = token.Load(tokenText);
if (success != true) {
wprintf(L"Expected token JSON.\n");
return;
}
textCompare.Clear();
textCompare.SetString(token.stringOf(L"access_token"));
bool sameText3 = textCompare.ContentsEqual(L"",true);
textCompare.Clear();
textCompare.SetString(token.stringOf(L"token_type"));
bool sameText4 = textCompare.ContentsEqual(L"Bearer",true);
if ((token.JsonTypeOf(L"access_token") != 1) || (sameText3 == true) || (sameText4 != true)) {
wprintf(L"Missing bearer token.\n");
return;
}
int seconds = token.IntOf(L"expires_in");
if ((seconds < 120) || (seconds > 86400)) {
wprintf(L"Unexpected token lifetime.\n");
return;
}
success = expires.AddSeconds(seconds);
if (success != true) {
wprintf(L"Could not prepare the request.\n");
return;
}
success = token.UpdateString(L"expires_at",expires.getAsTimestamp(false));
if (success != true) {
wprintf(L"Could not prepare the request.\n");
return;
}
success = token.WriteFile(L"qa_data/azure/storage-token.json");
if (success != true) {
wprintf(L"Could not persist token privately.\n");
return;
}
const wchar_t *accessToken = token.stringOf(L"access_token");
CkStringBuilderW endpoint;
success = endpoint.Append(config.stringOf(L"account"));
if (success != true) {
wprintf(L"Could not prepare the request.\n");
return;
}
success = endpoint.Append(L".blob.core.windows.net");
if (success != true) {
wprintf(L"Could not prepare the request.\n");
return;
}
// resourcePath is already URL-encoded. Encode each path segment once when adapting it.
// Keep slash separators; names and paths are case-sensitive.
const wchar_t *resourcePath = L"/examplecontainer/example.bin";
CkRestW rest;
rest.put_ConnectTimeoutMs(20000);
rest.put_IdleTimeoutMs(60000);
CkSocketW connection;
connection.put_RequireSslCertVerify(true);
connection.put_MaxReadIdleMs(60000);
connection.put_MaxSendIdleMs(60000);
success = connection.Connect(endpoint.getAsString(),443,true,20000);
if (success != true) {
wprintf(L"TLS connection failed; inspect diagnostics privately.\n");
return;
}
// Do not replay a write automatically after losing its response.
success = rest.UseConnection(connection,false);
if (success != true) {
wprintf(L"Could not prepare the request.\n");
return;
}
const wchar_t *responseText = 0;
CkXmlW result;
result.put_Strict(true);
success = rest.AddHeader(L"x-ms-version",L"2026-04-06");
if (success != true) {
wprintf(L"Could not prepare the request.\n");
return;
}
CkStringBuilderW bearer;
success = bearer.Append(L"Bearer ");
if (success != true) {
wprintf(L"Could not prepare the request.\n");
return;
}
success = bearer.Append(accessToken);
if (success != true) {
wprintf(L"Could not prepare the request.\n");
return;
}
success = rest.AddHeader(L"Authorization",bearer.getAsString());
if (success != true) {
wprintf(L"Could not prepare the request.\n");
return;
}
responseText = rest.fullRequestNoBody(L"HEAD",resourcePath);
if (rest.get_LastMethodSuccess() != true) {
wprintf(L"Request did not complete; outcome may be uncertain.\n");
return;
}
if (rest.get_ResponseStatusCode() != 200) {
wprintf(L"HTTP status: %d\n",rest.get_ResponseStatusCode());
wprintf(L"Azure error code: %s\n",rest.responseHdrByName(L"x-ms-error-code"));
wprintf(L"Request ID: %s\n",rest.responseHdrByName(L"x-ms-request-id"));
// Inspect any error body privately; do not log credentials, SAS URLs or payloads.
return;
}
wprintf(L"Storage token obtained and blob properties read.\n");
wprintf(L"ETag: %s\n",rest.responseHdrByName(L"ETag"));
}