Azure Batch - python ServicePrincipalCredentials equivalent

33 Views Asked by At

What is the equivalent of the following python code in C#?

from azure.common.credentials import ServicePrincipalCredentials

creds = ServicePrincipalCredentials(
        client_id=AZURE_CLIENT_ID,
        secret=AZURE_CLIENT_SECRET,
        tenant=AZURE_CLIENT_TENANT,
        resource="https://batch.core.windows.net/")

I tried:

var credential = new ClientSecretCredential(accountSettings.TenantId, accountSettings.ClientId, accountSettings.ClientSecret);
var token = await credential.GetTokenAsync(new TokenRequestContext(new[] { ".default" }));
var batchClient = new BatchServiceClient(new TokenCredentials(token.Token));

or

var tokenCredentials = await ApplicationTokenProvider.LoginSilentAsync($"https://login.microsoftonline.com/{accountSettings.TenantId}", accountSettings.ClientId, accountSettings.ClientSecret);
var batchClient = new BatchServiceClient(tokenCredentials);

using (BatchClient client = BatchClient.Open(batchClient)) {...}

but each time I call CommitAsync(), I get "Operation returned an invalid status code 'Unauthorized'".

if I use

var credential = new ClientCredential(accountSettings.ClientId, accountSettings.ClientSecret);
var authenticationContext = new AuthenticationContext($"https://login.microsoftonline.com/{accountSettings.TenantId}");
var result = await authenticationContext.AcquireTokenAsync("https://batch.core.windows.net/", credential);
var batchClient = new BatchServiceClient(new TokenCredentials(result.AccessToken));

or

var credential = new ClientSecretCredential(accountSettings.TenantId, accountSettings.ClientId, accountSettings.ClientSecret);
var token = await credential.GetTokenAsync(new TokenRequestContext(new[] { $"https://batch.core.windows.net/.default" }));
var batchServiceClient = new BatchServiceClient(new TokenCredentials(token.Token));

I get "Operation returned an invalid status code 'BadRequest'" (MissingRequiredProperty, Property=type, A required property was not specified in the request body.) Callstack: at Microsoft.Azure.Batch.Protocol.PoolOperations.d__6.MoveNext() at Microsoft.Azure.Batch.Protocol.BatchRequestBase2.<ExecuteRequestWithCancellationAsync>d__42.MoveNext() at Microsoft.Azure.Batch.Protocol.BatchRequestBase2.d__40.MoveNext()

1

There are 1 best solutions below

0
On

Apparently, I needed to add containerConfig.Type = "dockerCompatible";