Sample code for 30+ languages & platforms
Dart Requires Chilkat v11.6.0+

Azure Table: Read an Entity with Entra Client Credentials

See more Azure Table Service Examples

Supply tenant_id (directory GUID), client_id and client_secret in private storage.json. This confidential-client flow requests the Storage .default scope; it has no refresh token. 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.

Microsoft reference.

Chilkat Dart Downloads

Dart
import 'package:chilkat/chilkat.dart';

void main() {
  // StringBuilder compares text by value in every generated language.
  final textCompare = CkStringBuilder();
  // Assumes Chilkat is unlocked. See Global Unlock Sample.
  final config = CkJsonObject();
  config.strict = true;
  try {
    config.loadFile('qa_data/azure/storage.json');
  } on ChilkatException {
    print('Could not load private Azure configuration.');
    return;
  }

  textCompare.clear();
  textCompare.setString(config.stringOf('account'));
  final sameText1 = textCompare.contentsEqual('', true);
  if ((config.jsonTypeOf('account') != 1) || (sameText1)) {
    print('Supply the storage account name.');
    return;
  }

  final identity = CkRest();
  identity.connectTimeoutMs = 5000;
  identity.idleTimeoutMs = 30000;
  final expires = CkDateTime();
  try {
    expires.setFromCurrentSystemTime();
  } on ChilkatException {
    print('Could not prepare the request.');
    return;
  }

  textCompare.clear();
  textCompare.setString(config.stringOf('tenant_id'));
  final sameText2 = textCompare.contentsEqual('', true);
  if ((config.jsonTypeOf('tenant_id') != 1) || (sameText2)) {
    print('Missing string tenant_id.');
    return;
  }

  textCompare.clear();
  textCompare.setString(config.stringOf('client_id'));
  final sameText3 = textCompare.contentsEqual('', true);
  if ((config.jsonTypeOf('client_id') != 1) || (sameText3)) {
    print('Missing string client_id.');
    return;
  }

  textCompare.clear();
  textCompare.setString(config.stringOf('client_secret'));
  final sameText4 = textCompare.contentsEqual('', true);
  if ((config.jsonTypeOf('client_secret') != 1) || (sameText4)) {
    print('Missing string client_secret.');
    return;
  }

  final validate1 = CkStringBuilder();
  final alphabet1 = CkStringBuilder();
  try {
    validate1.append(config.stringOf('tenant_id'));
  } on ChilkatException {
    print('Could not prepare the request.');
    return;
  }

  try {
    alphabet1.append('0123456789abcdefABCDEF-');
  } on ChilkatException {
    print('Could not prepare the request.');
    return;
  }

  if ((validate1.length < 36) || (validate1.length > 36)) {
    print('Invalid tenant GUID length.');
    return;
  }

  var index1 = 0;
  while (index1 < validate1.length) {
    if (!alphabet1.contains(validate1.getRange(index1, 1, false), true)) {
      print('Invalid tenant GUID.');
      return;
    }

    index1++;
  }

  final identityTls = CkSocket();
  identityTls.requireSslCertVerify = true;
  identityTls.maxReadIdleMs = 30000;
  identityTls.maxSendIdleMs = 30000;
  try {
    identityTls.connect('login.microsoftonline.com', 443, true, 20000);
  } on ChilkatException {
    print('Identity TLS connection failed.');
    return;
  }

  try {
    identity.useConnection(identityTls, false);
  } on ChilkatException {
    print('Could not prepare the request.');
    return;
  }

  final tokenPath = CkStringBuilder();
  try {
    tokenPath.append('/');
  } on ChilkatException {
    print('Could not prepare the request.');
    return;
  }

  try {
    tokenPath.append(config.stringOf('tenant_id'));
  } on ChilkatException {
    print('Could not prepare the request.');
    return;
  }

  try {
    tokenPath.append('/oauth2/v2.0/token');
  } on ChilkatException {
    print('Could not prepare the request.');
    return;
  }

  try {
    identity.addQueryParam('grant_type', 'client_credentials');
  } on ChilkatException {
    print('Could not prepare the request.');
    return;
  }

  try {
    identity.addQueryParam('scope', 'https://storage.azure.com/.default');
  } on ChilkatException {
    print('Could not prepare the request.');
    return;
  }

  try {
    identity.addQueryParam('client_id', config.stringOf('client_id'));
  } on ChilkatException {
    print('Could not prepare the request.');
    return;
  }

  try {
    identity.addQueryParam('client_secret', config.stringOf('client_secret'));
  } on ChilkatException {
    print('Could not prepare the request.');
    return;
  }

  // FullRequestFormUrlEncoded places the parameters in the POST body, not the URL.
  final String tokenText;
  try {
    tokenText = identity.fullRequestFormUrlEncoded('POST', tokenPath.getAsString());
  } on ChilkatException {
    print('Token request did not complete.');
    return;
  }

  if (identity.responseStatusCode != 200) {
    print('Token request failed; keep its body and diagnostics private.');
    return;
  }

  final token = CkJsonObject();
  token.strict = true;
  try {
    token.load(tokenText);
  } on ChilkatException {
    print('Expected token JSON.');
    return;
  }

  textCompare.clear();
  textCompare.setString(token.stringOf('access_token'));
  final sameText5 = textCompare.contentsEqual('', true);
  if ((token.jsonTypeOf('access_token') != 1) || (sameText5)) {
    print('Missing string access_token.');
    return;
  }

  textCompare.clear();
  textCompare.setString(token.stringOf('token_type'));
  final sameText6 = textCompare.contentsEqual('Bearer', true);
  if (!sameText6) {
    print('Expected a bearer token.');
    return;
  }

  if (token.jsonTypeOf('expires_in') != 2) {
    print('Invalid token lifetime type.');
    return;
  }

  final validate2 = CkStringBuilder();
  final alphabet2 = CkStringBuilder();
  try {
    validate2.append(token.stringOf('expires_in'));
  } on ChilkatException {
    print('Could not prepare the request.');
    return;
  }

  try {
    alphabet2.append('0123456789');
  } on ChilkatException {
    print('Could not prepare the request.');
    return;
  }

  if ((validate2.length < 1) || (validate2.length > 6)) {
    print('Invalid token lifetime length.');
    return;
  }

  var index2 = 0;
  while (index2 < validate2.length) {
    if (!alphabet2.contains(validate2.getRange(index2, 1, false), true)) {
      print('Invalid token lifetime.');
      return;
    }

    index2++;
  }

  final seconds = token.intOf('expires_in');
  if ((seconds < 120) || (seconds > 86400)) {
    print('Unexpected token lifetime.');
    return;
  }

  try {
    expires.addSeconds(seconds);
  } on ChilkatException {
    print('Could not prepare the request.');
    return;
  }

  final now = CkDateTime();
  try {
    now.setFromCurrentSystemTime();
  } on ChilkatException {
    print('Could not prepare the request.');
    return;
  }

  if (expires.diffSeconds(now) <= 60) {
    print('Token expired while the request was in progress.');
    return;
  }

  final saved = CkJsonObject();
  try {
    saved.updateString('access_token', token.stringOf('access_token'));
  } on ChilkatException {
    print('Could not prepare the request.');
    return;
  }

  try {
    saved.updateString('expires_at', expires.getAsTimestamp(false));
  } on ChilkatException {
    print('Could not prepare the request.');
    return;
  }

  try {
    saved.updateString('resource', 'https://storage.azure.com/');
  } on ChilkatException {
    print('Could not prepare the request.');
    return;
  }

  try {
    saved.writeFile('qa_data/azure/table-token.json');
  } on ChilkatException {
    print('Could not save the private token file.');
    return;
  }

  final accountText = CkStringBuilder();
  try {
    accountText.append(config.stringOf('account'));
  } on ChilkatException {
    print('Could not prepare the request.');
    return;
  }

  if ((accountText.length < 3) || (accountText.length > 24)) {
    print('Storage account names need 3-24 lowercase letters or digits.');
    return;
  }

  final allowedAccountChars = CkStringBuilder();
  try {
    allowedAccountChars.append('abcdefghijklmnopqrstuvwxyz0123456789');
  } on ChilkatException {
    print('Could not prepare the request.');
    return;
  }

  var charIndex = 0;
  while (charIndex < accountText.length) {
    if (!allowedAccountChars.contains(accountText.getRange(charIndex, 1, false), true)) {
      print('Storage account names need lowercase letters or digits.');
      return;
    }

    charIndex++;
  }

  final endpoint = CkStringBuilder();
  try {
    endpoint.append(config.stringOf('account'));
  } on ChilkatException {
    print('Could not prepare the request.');
    return;
  }

  try {
    endpoint.append('.table.core.windows.net');
  } on ChilkatException {
    print('Could not prepare the request.');
    return;
  }

  // Table names contain only letters and digits and are case-insensitive.
  // Entity PartitionKey and RowKey values are case-sensitive.
  var resourcePath = '/ExampleCustomers()';
  final rest = CkRest();
  rest.connectTimeoutMs = 20000;
  rest.idleTimeoutMs = 60000;
  final connection = CkSocket();
  connection.requireSslCertVerify = true;
  connection.maxReadIdleMs = 60000;
  connection.maxSendIdleMs = 60000;
  try {
    connection.connect(endpoint.getAsString(), 443, true, 20000);
  } on ChilkatException {
    print('TLS connection failed; inspect diagnostics privately.');
    return;
  }

  // Do not replay a write automatically after losing its response.
  try {
    rest.useConnection(connection, false);
  } on ChilkatException {
    print('Could not prepare the request.');
    return;
  }

  var responseText = '';
  final result = CkJsonObject();
  result.strict = true;
  try {
    rest.addHeader('DataServiceVersion', '3.0;NetFx');
  } on ChilkatException {
    print('Could not prepare the request.');
    return;
  }

  try {
    rest.addHeader('MaxDataServiceVersion', '3.0;NetFx');
  } on ChilkatException {
    print('Could not prepare the request.');
    return;
  }

  try {
    rest.addHeader('Content-Type', 'application/json');
  } on ChilkatException {
    print('Could not prepare the request.');
    return;
  }

  try {
    rest.addHeader('Accept', 'application/json;odata=minimalmetadata');
  } on ChilkatException {
    print('Could not prepare the request.');
    return;
  }

  try {
    rest.addHeader('x-ms-version', '2026-04-06');
  } on ChilkatException {
    print('Could not prepare the request.');
    return;
  }

  final authorization = CkStringBuilder();
  try {
    authorization.append('Bearer ');
  } on ChilkatException {
    print('Could not prepare the request.');
    return;
  }

  try {
    authorization.append(token.stringOf('access_token'));
  } on ChilkatException {
    print('Could not prepare the request.');
    return;
  }

  try {
    rest.addHeader('Authorization', authorization.getAsString());
  } on ChilkatException {
    print('Could not prepare the request.');
    return;
  }

  final partitionKey = 'customers-west';
  final rowKey = 'customer-001';
  final encodedPk = CkStringBuilder();
  try {
    encodedPk.append(partitionKey);
  } on ChilkatException {
    print('Could not prepare the request.');
    return;
  }

  final escapedencodedPk = encodedPk.replace('\'', '\'\'');
  try {
    encodedPk.encode('url_rfc3986', 'utf-8');
  } on ChilkatException {
    print('Could not prepare the request.');
    return;
  }

  final encodedRk = CkStringBuilder();
  try {
    encodedRk.append(rowKey);
  } on ChilkatException {
    print('Could not prepare the request.');
    return;
  }

  final escapedencodedRk = encodedRk.replace('\'', '\'\'');
  try {
    encodedRk.encode('url_rfc3986', 'utf-8');
  } on ChilkatException {
    print('Could not prepare the request.');
    return;
  }

  // Escape apostrophes for OData first, then percent-encode each key once.
  final entityPath = CkStringBuilder();
  try {
    entityPath.append('/ExampleCustomers(PartitionKey=\'');
  } on ChilkatException {
    print('Could not prepare the request.');
    return;
  }

  try {
    entityPath.append(encodedPk.getAsString());
  } on ChilkatException {
    print('Could not prepare the request.');
    return;
  }

  try {
    entityPath.append('\',RowKey=\'');
  } on ChilkatException {
    print('Could not prepare the request.');
    return;
  }

  try {
    entityPath.append(encodedRk.getAsString());
  } on ChilkatException {
    print('Could not prepare the request.');
    return;
  }

  try {
    entityPath.append('\')');
  } on ChilkatException {
    print('Could not prepare the request.');
    return;
  }

  resourcePath = entityPath.getAsString();
  try {
    now.setFromCurrentSystemTime();
  } on ChilkatException {
    print('Could not prepare the request.');
    return;
  }

  if (expires.diffSeconds(now) <= 60) {
    print('Reacquire a token before the Table request.');
    return;
  }

  try {
    responseText = rest.fullRequestNoBody('GET', resourcePath);
  } on ChilkatException {
    print('Request did not complete; inspect the target before retrying a write.');
    return;
  }

  if (rest.responseStatusCode != 200) {
    print('HTTP status: ${rest.responseStatusCode}');
    print('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;
  }

  try {
    result.load(responseText);
  } on ChilkatException {
    print('Expected well-formed JSON.');
    return;
  }

  textCompare.clear();
  textCompare.setString(result.stringOf('PartitionKey'));
  final sameText7 = textCompare.contentsEqual('', true);
  if ((result.jsonTypeOf('PartitionKey') != 1) || (sameText7)) {
    print('Missing string PartitionKey.');
    return;
  }

  textCompare.clear();
  textCompare.setString(result.stringOf('RowKey'));
  final sameText8 = textCompare.contentsEqual('', true);
  if ((result.jsonTypeOf('RowKey') != 1) || (sameText8)) {
    print('Missing string RowKey.');
    return;
  }

  textCompare.clear();
  textCompare.setString(result.stringOf('PartitionKey'));
  final sameText9 = textCompare.contentsEqual(partitionKey, true);
  textCompare.clear();
  textCompare.setString(result.stringOf('RowKey'));
  final sameText10 = textCompare.contentsEqual(rowKey, true);
  if ((!sameText9) || (!sameText10)) {
    print('Returned entity keys do not match.');
    return;
  }

  print('Storage token obtained and Table entity retrieved.');
}