I am trying to change a working example from internet:
IAzure azure = Azure.Configure()
.Authenticate(credentials)
.WithSubscription(credentials.DefaultSubscriptionId)
into Azure Device authentication like this:
AzureCredentials accessTokenCredentials = GetAzureAccessTokenCredentials(credentials,
AzureEndPointApi.Management,
environment);
IAzure az = Azure.Configure().Authenticate(accessTokenCredentials)
This still works unless I need to call some function which use Management API and Graph API together like this:
private static async Task<IServicePrincipal> AddAccountToRoles(IAzure azureManagement, IAzure azureGraph, IActiveDirectoryApplication activeDirectoryApp)
{
var role = azureGraph.AccessManagement.ServicePrincipals.Define($"{activeDirectoryApp.Name}-contributor")
.WithExistingApplication(activeDirectoryApp)
.WithNewRoleInSubscription(BuiltInRole.Contributor, azureGraph.SubscriptionId);
var result = await role.CreateAsync();
return result;
}
CreateAsync calls both Graph AP and Management API according to to Fiddler. So I suppose it needs two different access tokens (one for each service), isn't it?
So I changed the code into:
var restClient = RestClient
.Configure()
.WithBaseUri(AzureDelegatingHandler.GetBaseUri(environment, AzureEndPointApi.Management))
.WithEnvironment(environment)
.WithCredentials(GetAzureAccessTokenCredentials(credentials, AzureEndPointApi.Management, environment))
.WithBaseUri(AzureDelegatingHandler.GetBaseUri(environment, AzureEndPointApi.Graph))
.WithEnvironment(environment)
.WithCredentials(GetAzureAccessTokenCredentials(credentials, AzureEndPointApi.Graph, environment))
.Build();
IAzure azure = Azure
.Authenticate(restClient, credentials.TenantId)
.WithSubscription(credentials.DefaultSubscriptionId);
public static string GetBaseUri(AzureEnvironment environment, AzureEndPointApi azureEndPointApi)
{
switch (azureEndPointApi)
{
case AzureEndPointApi.Graph:
return environment.GraphEndpoint;
case AzureEndPointApi.Management:
return environment.ManagementEndpoint;
default:
throw new NotSupportedException(azureEndPointApi.ToString());
}
}
But this code serves incorrect access token - not based on REST API endpoint base uri.
What do I wrong?
AzureCredentials has constructor with two access tokens, one for each API.