Azure Table: Read an Entity with Azure VM Managed Identity
See more Azure Table Service Examples
Run on an Azure VM with a system-assigned identity, or supply managed_client_id for an attached user-assigned identity. The fixed IMDS endpoint is specific to VMs; App Service and Azure Arc use different flows. Assign Storage Table Data Reader or an appropriate Table data role. A management-plane Contributor role alone is not sufficient. Acquires a Storage-audience token and actually uses it to retrieve an entity, without an account key.
Saves only access_token, expires_at and resource to private table-token.json, replacing the prior cache. Uses request-start time for expiry. Reacquire before expiry; do not print the token or embed a client secret in a public client. This sample stops on identity errors rather than applying a generic retry policy.
Targets Azure Storage Table service in the public cloud, not Azure Cosmos DB for Table. Uses Chilkat 11.6.0 or later and an unlocked library. Direct data requests pin x-ms-version 2026-04-06 and OData 3.0. Shared Key examples read private qa_data/azure/storage.json with account and access_key string fields. Authentication examples explain their additional fields. Create private local directories before running; keep credentials, tokens, SAS, entity values, checkpoints and diagnostics outside public content and source control.
HTTPS certificates are verified. Transport completion and HTTP status are checked separately. Writes are not automatically retried after an uncertain outcome. Entity keys, ETags and continuation tokens remain strings. Examples operate on the existing ExampleCustomers table unless noted; review the targets before adapting them. Microsoft Entra ID with suitable Table data roles is preferred where available.
Chilkat B4X Downloads
Dim success As Boolean = False
' StringBuilder compares text by value in every generated language.
Dim textCompare As ChilkatStringBuilder
textCompare.Initialize
' Assumes Chilkat is unlocked. See Global Unlock Sample.
success = False
Dim config As ChilkatJsonObject
config.Initialize
config.Strict = True
success = config.LoadFile("qa_data/azure/storage.json")
If success <> True Then
Log("Could not load private Azure configuration.")
Return
End If
textCompare.Clear
textCompare.SetString(config.StringOf("account"))
Dim sameText1 As Boolean = textCompare.ContentsEqual("", True)
If (config.JsonTypeOf("account") <> 1) Or (sameText1 = True) Then
Log("Supply the storage account name.")
Return
End If
Dim identity As ChilkatRest
identity.Initialize("identity")
identity.ConnectTimeoutMs = 5000
identity.IdleTimeoutMs = 30000
Dim expires As ChilkatDateTime
expires.Initialize
success = expires.SetFromCurrentSystemTime
If success <> True Then
Log("Could not prepare the request.")
Return
End If
' Fixed Azure VM IMDS endpoint; no proxy, no redirects, no automatic reconnect.
success = identity.Connect("169.254.169.254", 80, False, False)
If success <> True Then
Log("IMDS requires an Azure VM with managed identity enabled.")
Return
End If
success = identity.AddHeader("Metadata", "true")
If success <> True Then
Log("Could not prepare the request.")
Return
End If
success = identity.AddQueryParam("api-version", "2018-02-01")
If success <> True Then
Log("Could not prepare the request.")
Return
End If
success = identity.AddQueryParam("resource", "https://storage.azure.com/")
If success <> True Then
Log("Could not prepare the request.")
Return
End If
If config.HasMember("managed_client_id") = True Then
textCompare.Clear
textCompare.SetString(config.StringOf("managed_client_id"))
Dim sameText2 As Boolean = textCompare.ContentsEqual("", True)
If (config.JsonTypeOf("managed_client_id") <> 1) Or (sameText2 = True) Then
Log("Missing string managed_client_id.")
Return
End If
success = identity.AddQueryParam("client_id", config.StringOf("managed_client_id"))
If success <> True Then
Log("Could not prepare the request.")
Return
End If
End If
Dim tokenText As String = identity.FullRequestNoBody("GET", "/metadata/identity/oauth2/token")
If identity.LastMethodSuccess <> True Then
Log("Token request did not complete.")
Return
End If
If identity.ResponseStatusCode <> 200 Then
Log("Token request failed; keep its body and diagnostics private.")
Return
End If
Dim token As ChilkatJsonObject
token.Initialize
token.Strict = True
success = token.Load(tokenText)
If success <> True Then
Log("Expected token JSON.")
Return
End If
textCompare.Clear
textCompare.SetString(token.StringOf("access_token"))
Dim sameText3 As Boolean = textCompare.ContentsEqual("", True)
If (token.JsonTypeOf("access_token") <> 1) Or (sameText3 = True) Then
Log("Missing string access_token.")
Return
End If
textCompare.Clear
textCompare.SetString(token.StringOf("token_type"))
Dim sameText4 As Boolean = textCompare.ContentsEqual("Bearer", True)
If sameText4 <> True Then
Log("Expected a bearer token.")
Return
End If
If (token.JsonTypeOf("expires_in") <> 2) And (token.JsonTypeOf("expires_in") <> 1) Then
Log("Invalid token lifetime type.")
Return
End If
Dim validate3 As ChilkatStringBuilder
validate3.Initialize
Dim alphabet3 As ChilkatStringBuilder
alphabet3.Initialize
success = validate3.Append(token.StringOf("expires_in"))
If success <> True Then
Log("Could not prepare the request.")
Return
End If
success = alphabet3.Append("0123456789")
If success <> True Then
Log("Could not prepare the request.")
Return
End If
If (validate3.Length < 1) Or (validate3.Length > 6) Then
Log("Invalid token lifetime length.")
Return
End If
Dim index3 As Int = 0
Do While (index3 < validate3.Length)
If alphabet3.Contains(validate3.GetRange(index3, 1, False), True) <> True Then
Log("Invalid token lifetime.")
Return
End If
index3 = index3 + 1
Loop
Dim seconds As Int = token.IntOf("expires_in")
If (seconds < 120) Or (seconds > 86400) Then
Log("Unexpected token lifetime.")
Return
End If
success = expires.AddSeconds(seconds)
If success <> True Then
Log("Could not prepare the request.")
Return
End If
Dim now As ChilkatDateTime
now.Initialize
success = now.SetFromCurrentSystemTime
If success <> True Then
Log("Could not prepare the request.")
Return
End If
If expires.DiffSeconds(now) <= 60 Then
Log("Token expired while the request was in progress.")
Return
End If
Dim saved As ChilkatJsonObject
saved.Initialize
success = saved.UpdateString("access_token", token.StringOf("access_token"))
If success <> True Then
Log("Could not prepare the request.")
Return
End If
success = saved.UpdateString("expires_at", expires.GetAsTimestamp(False))
If success <> True Then
Log("Could not prepare the request.")
Return
End If
success = saved.UpdateString("resource", "https://storage.azure.com/")
If success <> True Then
Log("Could not prepare the request.")
Return
End If
success = saved.WriteFile("qa_data/azure/table-token.json")
If success <> True Then
Log("Could not save the private token file.")
Return
End If
Dim accountText As ChilkatStringBuilder
accountText.Initialize
success = accountText.Append(config.StringOf("account"))
If success <> True Then
Log("Could not prepare the request.")
Return
End If
If (accountText.Length < 3) Or (accountText.Length > 24) Then
Log("Storage account names need 3-24 lowercase letters or digits.")
Return
End If
Dim allowedAccountChars As ChilkatStringBuilder
allowedAccountChars.Initialize
success = allowedAccountChars.Append("abcdefghijklmnopqrstuvwxyz0123456789")
If success <> True Then
Log("Could not prepare the request.")
Return
End If
Dim charIndex As Int = 0
Do While (charIndex < accountText.Length)
If allowedAccountChars.Contains(accountText.GetRange(charIndex, 1, False), True) <> True Then
Log("Storage account names need lowercase letters or digits.")
Return
End If
charIndex = charIndex + 1
Loop
Dim endpoint As ChilkatStringBuilder
endpoint.Initialize
success = endpoint.Append(config.StringOf("account"))
If success <> True Then
Log("Could not prepare the request.")
Return
End If
success = endpoint.Append(".table.core.windows.net")
If success <> True Then
Log("Could not prepare the request.")
Return
End If
' Table names contain only letters and digits and are case-insensitive.
' Entity PartitionKey and RowKey values are case-sensitive.
Dim resourcePath As String = "/ExampleCustomers()"
Dim rest As ChilkatRest
rest.Initialize("rest")
rest.ConnectTimeoutMs = 20000
rest.IdleTimeoutMs = 60000
Dim connection As ChilkatSocket
connection.Initialize("connection")
connection.RequireSslCertVerify = True
connection.MaxReadIdleMs = 60000
connection.MaxSendIdleMs = 60000
success = connection.Connect(endpoint.GetAsString, 443, True, 20000)
If success <> True Then
Log("TLS connection failed; inspect diagnostics privately.")
Return
End If
' Do not replay a write automatically after losing its response.
success = rest.UseConnection(connection, False)
If success <> True Then
Log("Could not prepare the request.")
Return
End If
Dim responseText As String
Dim result As ChilkatJsonObject
result.Initialize
result.Strict = True
success = rest.AddHeader("DataServiceVersion", "3.0;NetFx")
If success <> True Then
Log("Could not prepare the request.")
Return
End If
success = rest.AddHeader("MaxDataServiceVersion", "3.0;NetFx")
If success <> True Then
Log("Could not prepare the request.")
Return
End If
success = rest.AddHeader("Content-Type", "application/json")
If success <> True Then
Log("Could not prepare the request.")
Return
End If
success = rest.AddHeader("Accept", "application/json;odata=minimalmetadata")
If success <> True Then
Log("Could not prepare the request.")
Return
End If
success = rest.AddHeader("x-ms-version", "2026-04-06")
If success <> True Then
Log("Could not prepare the request.")
Return
End If
Dim authorization As ChilkatStringBuilder
authorization.Initialize
success = authorization.Append("Bearer ")
If success <> True Then
Log("Could not prepare the request.")
Return
End If
success = authorization.Append(token.StringOf("access_token"))
If success <> True Then
Log("Could not prepare the request.")
Return
End If
success = rest.AddHeader("Authorization", authorization.GetAsString)
If success <> True Then
Log("Could not prepare the request.")
Return
End If
Dim partitionKey As String = "customers-west"
Dim rowKey As String = "customer-001"
Dim encodedPk As ChilkatStringBuilder
encodedPk.Initialize
success = encodedPk.Append(partitionKey)
If success <> True Then
Log("Could not prepare the request.")
Return
End If
Dim escapedencodedPk As Int = encodedPk.Replace("'", "''")
success = encodedPk.Encode("url_rfc3986", "utf-8")
If success <> True Then
Log("Could not prepare the request.")
Return
End If
Dim encodedRk As ChilkatStringBuilder
encodedRk.Initialize
success = encodedRk.Append(rowKey)
If success <> True Then
Log("Could not prepare the request.")
Return
End If
Dim escapedencodedRk As Int = encodedRk.Replace("'", "''")
success = encodedRk.Encode("url_rfc3986", "utf-8")
If success <> True Then
Log("Could not prepare the request.")
Return
End If
' Escape apostrophes for OData first, then percent-encode each key once.
Dim entityPath As ChilkatStringBuilder
entityPath.Initialize
success = entityPath.Append("/ExampleCustomers(PartitionKey='")
If success <> True Then
Log("Could not prepare the request.")
Return
End If
success = entityPath.Append(encodedPk.GetAsString)
If success <> True Then
Log("Could not prepare the request.")
Return
End If
success = entityPath.Append("',RowKey='")
If success <> True Then
Log("Could not prepare the request.")
Return
End If
success = entityPath.Append(encodedRk.GetAsString)
If success <> True Then
Log("Could not prepare the request.")
Return
End If
success = entityPath.Append("')")
If success <> True Then
Log("Could not prepare the request.")
Return
End If
resourcePath = entityPath.GetAsString
success = now.SetFromCurrentSystemTime
If success <> True Then
Log("Could not prepare the request.")
Return
End If
If expires.DiffSeconds(now) <= 60 Then
Log("Reacquire a token before the Table request.")
Return
End If
responseText = rest.FullRequestNoBody("GET", resourcePath)
If rest.LastMethodSuccess <> True Then
Log("Request did not complete; inspect the target before retrying a write.")
Return
End If
If rest.ResponseStatusCode <> 200 Then
Log("HTTP status: " & rest.ResponseStatusCode)
Log("Request ID: " & rest.ResponseHdrByName("x-ms-request-id"))
' 404 is missing, 409 is conflict, and 412 is a stale ETag: none are success.
' Keep response bodies private. Reconcile uncertain writes before retrying.
Return
End If
success = result.Load(responseText)
If success <> True Then
Log("Expected well-formed JSON.")
Return
End If
textCompare.Clear
textCompare.SetString(result.StringOf("PartitionKey"))
Dim sameText5 As Boolean = textCompare.ContentsEqual("", True)
If (result.JsonTypeOf("PartitionKey") <> 1) Or (sameText5 = True) Then
Log("Missing string PartitionKey.")
Return
End If
textCompare.Clear
textCompare.SetString(result.StringOf("RowKey"))
Dim sameText6 As Boolean = textCompare.ContentsEqual("", True)
If (result.JsonTypeOf("RowKey") <> 1) Or (sameText6 = True) Then
Log("Missing string RowKey.")
Return
End If
textCompare.Clear
textCompare.SetString(result.StringOf("PartitionKey"))
Dim sameText7 As Boolean = textCompare.ContentsEqual(partitionKey, True)
textCompare.Clear
textCompare.SetString(result.StringOf("RowKey"))
Dim sameText8 As Boolean = textCompare.ContentsEqual(rowKey, True)
If (sameText7 <> True) Or (sameText8 <> True) Then
Log("Returned entity keys do not match.")
Return
End If
Log("Storage token obtained and Table entity retrieved.")