简体   繁体   中英

How to authenticate with Azure Resource Manager using managed identity in C#

I am trying to use the managedIdentity to get a token that I can then use to list resources in the resource group. I am getting an error when attempting to get the token. The GetToken() api seems to be adding other strings (offline_access openid) internally to the scope I provided and fails that the scope is not a valid url. From the error, it appears that I am not using the api correctly. But I am also following the documentation. Could some one please help track down what the issue is in my code.

Code:

var managedIdentityCredential = new DefaultAzureCredential(new DefaultAzureCredentialOptions { ManagedIdentityClientId = managedIdentityId });
var azureServiceTokenProvider = new AzureServiceTokenProvider("RunAs=App");
AccessToken accessToken = managedIdentityCredential.GetToken(new TokenRequestContext(new string[] { "https://management.azure.com/" }));

Error: Azure.Identity.AuthenticationFailedException: SharedTokenCacheCredential authentication failed. ---> Microsoft.Identity.Client.MsalServiceException: AADSTS70011: The provided request must include a 'scope' input parameter. The provided value for the input parameter 'scope' is not valid. The scope https://management.azure.com/ offline_access openid profile is not valid. The scope format is invalid. Scope must be in a valid URI form https://example/scope or a valid Guid <guid/scope>.

To get the token with MSI(managed identity), make sure you ran the code in the Azure services that support the managed identity .

After enabling the system-assigned MSI for the service, then use the code below directly.

var azureServiceTokenProvider = new AzureServiceTokenProvider("RunAs=App");
string accessToken = azureServiceTokenProvider.GetAccessTokenAsync("https://management.azure.com/").Result;
Console.WriteLine(accessToken)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM