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 Lua Downloads
local chilkat = require("chilkat")
-- StringBuilder compares text by value in every generated language.
local textCompare = chilkat.StringBuilder.new()
-- Assumes Chilkat is unlocked. See Global Unlock Sample.
local success = false
local config = chilkat.JsonObject.new()
config.strict = true
success = config:load_file("qa_data/azure/storage.json")
if not success then
print("Could not load private Azure configuration.")
return
end
textCompare:clear()
textCompare:set_string(config:string_of("account"))
local sameText1 = textCompare:contents_equal("", true)
if (config:json_type_of("account") ~= 1) or (sameText1) then
print("Supply the storage account name.")
return
end
local identity = chilkat.Rest.new()
identity.connect_timeout_ms = 20000
identity.idle_timeout_ms = 60000
local expires = chilkat.DateTime.new()
success = expires:set_from_current_system_time()
if not success then
print("Could not prepare the request.")
return
end
-- 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("169.254.169.254", 80, false, false)
if not success then
print("IMDS is available only on an eligible Azure VM.")
return
end
success = identity:add_header("Metadata", "true")
if not success then
print("Could not prepare the request.")
return
end
success = identity:add_query_param("api-version", "2018-02-01")
if not success then
print("Could not prepare the request.")
return
end
success = identity:add_query_param("resource", "https://storage.azure.com/")
if not success then
print("Could not prepare the request.")
return
end
-- Optional user-assigned identity. Omit for the VM's system-assigned identity.
if config:has_member("managed_client_id") then
textCompare:clear()
textCompare:set_string(config:string_of("managed_client_id"))
local sameText2 = textCompare:contents_equal("", true)
if (config:json_type_of("managed_client_id") ~= 1) or (sameText2) then
print("Invalid managed_client_id.")
return
end
success = identity:add_query_param("client_id", config:string_of("managed_client_id"))
if not success then
print("Could not prepare the request.")
return
end
end
local tokenText = identity:full_request_no_body("GET", "/metadata/identity/oauth2/token")
if not identity.last_method_success then
print("Token request did not complete; inspect diagnostics privately.")
return
end
if identity.response_status_code ~= 200 then
print("Token request failed; inspect the status privately, never print the response token.")
return
end
local token = chilkat.JsonObject.new()
token.strict = true
success = token:load(tokenText)
if not success then
print("Expected token JSON.")
return
end
textCompare:clear()
textCompare:set_string(token:string_of("access_token"))
local sameText3 = textCompare:contents_equal("", true)
textCompare:clear()
textCompare:set_string(token:string_of("token_type"))
local sameText4 = textCompare:contents_equal("Bearer", true)
if (token:json_type_of("access_token") ~= 1) or ((sameText3) or (not sameText4)) then
print("Missing bearer token.")
return
end
local seconds = token:int_of("expires_in")
if (seconds < 120) or (seconds > 86400) then
print("Unexpected token lifetime.")
return
end
success = expires:add_seconds(seconds)
if not success then
print("Could not prepare the request.")
return
end
success = token:update_string("expires_at", expires:get_as_timestamp(false))
if not success then
print("Could not prepare the request.")
return
end
success = token:write_file("qa_data/azure/storage-token.json")
if not success then
print("Could not persist token privately.")
return
end
local accessToken = token:string_of("access_token")
local endpoint = chilkat.StringBuilder.new()
success = endpoint:append(config:string_of("account"))
if not success then
print("Could not prepare the request.")
return
end
success = endpoint:append(".blob.core.windows.net")
if not success then
print("Could not prepare the request.")
return
end
-- resourcePath is already URL-encoded. Encode each path segment once when adapting it.
-- Keep slash separators; names and paths are case-sensitive.
local resourcePath = "/examplecontainer/example.bin"
local rest = chilkat.Rest.new()
rest.connect_timeout_ms = 20000
rest.idle_timeout_ms = 60000
local connection = chilkat.Socket.new()
connection.require_ssl_cert_verify = true
connection.max_read_idle_ms = 60000
connection.max_send_idle_ms = 60000
success = connection:connect(endpoint:get_as_string(), 443, true, 20000)
if not success then
print("TLS connection failed; inspect diagnostics privately.")
return
end
-- Do not replay a write automatically after losing its response.
success = rest:use_connection(connection, false)
if not success then
print("Could not prepare the request.")
return
end
local result = chilkat.Xml.new()
result.strict = true
success = rest:add_header("x-ms-version", "2026-04-06")
if not success then
print("Could not prepare the request.")
return
end
local bearer = chilkat.StringBuilder.new()
success = bearer:append("Bearer ")
if not success then
print("Could not prepare the request.")
return
end
success = bearer:append(accessToken)
if not success then
print("Could not prepare the request.")
return
end
success = rest:add_header("Authorization", bearer:get_as_string())
if not success then
print("Could not prepare the request.")
return
end
local responseText = rest:full_request_no_body("HEAD", resourcePath)
if not rest.last_method_success then
print("Request did not complete; outcome may be uncertain.")
return
end
if rest.response_status_code ~= 200 then
print("HTTP status: " .. rest.response_status_code)
print("Azure error code: " .. rest:response_hdr_by_name("x-ms-error-code"))
print("Request ID: " .. rest:response_hdr_by_name("x-ms-request-id"))
-- Inspect any error body privately; do not log credentials, SAS URLs or payloads.
return
end
print("Storage token obtained and blob properties read.")
print("ETag: " .. rest:response_hdr_by_name("ETag"))