I am using Azure.Identity 1.7 and using VS 2022 , trying to get the token using DefaultAzureCredential,
var tokenCredential = new DefaultAzureCredential();
var accessToken = await tokenCredential.GetTokenAsync(new TokenRequestContext(new[] { _configuration.GetSection("scope")?.Value }));
I am log in with my credential everwhere, VS 2022, powershell, azure cli, but still I am getting below error while trying to get token,
What I am missing here?
Error message: Azure PowerShell authentication failed due to an unknown error. See the troubleshooting guide for more information. https://aka.ms/azsdk/net/identity/powershellcredential/troubleshoot #< CLIXML
x001B[91mGet-AzAccessToken: x000D__x000Ax001B[96mLine |x000D__x000Ax001B[96m 12 | x001B[0m $token = x001B[96mGet-AzAccessToken -ResourceUrl 'api://d39cb913-ef82-48ba-9b1_x001B_[0m .x000D__x000Ax001B[96m | x001B[91m ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~x000D__x000Ax001B[91m_x001B_[96m | x001B[91mSharedTokenCacheCredential authentication unavailable. Token acquisition failed for user aa.bb#cc.com. Ensure that you have authenticated with a developer tool that supports Azure single sign on.
Related
I am trying to get a Key Vault Secret from Azure but getting error.
Here is my code
var client = new SecretClient(new Uri("https://eq-azure-kv-keyvaultname.vault.azure.net/")
, new DefaultAzureCredential());
var bearertokenentry = (await client.GetSecretAsync(Constants.Azure.KeyVault.SUBSCRIPTION_TOKENS)).Value;
Error I get is
I am using VS 2022 and logged in with my Azure account.
I am using following Azure packages
I've tried following this tutorial in order to authenticate my service bus against DefaultAzureCredentials, however, I get a 401.
I'm using the following code in the set-up:
services.AddAzureClients(x =>
{
x.AddServiceBusClientWithNamespace("myns.servicebus.windows.net")
.WithCredential(new Azure.Identity.DefaultAzureCredential());
});
I then call the SB client like this:
var sender = client.CreateSender("myqueue");
var message = new ServiceBusMessage(Encoding.UTF8.GetBytes("test"));
await sender.SendMessageAsync(message);
When I call SendMessageAsync I get a 401 error:
fail: Azure-Messaging-ServiceBus[82]
An exception occurred while creating send link for Identifier: myqueue-578624f3-f732-4a9b-2ab0-9adc01949a5a. Error Message:
'System.UnauthorizedAccessException: Put token failed. status-code:
401, status-description: InvalidIssuer: Token issuer is invalid.
TrackingId:cde3a89c-8108-48d1-8b8f-dacde18e176f,
SystemTracker:NoSystemTracker, Timestamp:2021-05-19T07:18:44.
Before I run this, I call az login. I have access to the the namespace to both send and receive. My guess is that I need to allocate some kind of permission between the service bus and ... something - but since I'm running this as a console app, I'm running with my own credentials. Clearly there's something about managed identity that I don't understand.
EDIT:
Following advice from #juunas, I tried the following:
services.AddHostedService<ConsoleHostedService>();
services.AddAzureClients(x =>
{
//var creds = new Azure.Identity.EnvironmentCredential(); // 1st - EnvironmentCredential authentication unavailable. Environment variables are not fully configured.'
//var creds = new Azure.Identity.ManagedIdentityCredential(); // 2nd - No Managed Identity endpoint found
//var creds = new Azure.Identity.SharedTokenCacheCredential(); // 3rd - 'SharedTokenCacheCredential authentication unavailable. No accounts were found in the cache.'
//var creds = new Azure.Identity.VisualStudioCodeCredential(); // 4th - 'Stored credentials not found. Need to authenticate user in VSCode Azure Account.'
//var creds = new Azure.Identity.AzureCliCredential(); // 5th
var creds = new Azure.Identity.DefaultAzureCredential();
x.AddServiceBusClientWithNamespace("myns.servicebus.windows.net")
.WithCredential(creds);
It says the "token issuer is invalid".
That means it got an access token, but it was issued by the wrong Azure AD tenant.
The Az CLI allows you to specify the Azure AD tenant id with the -t tenant-id-here argument on az login.
DefaultAzureCredential could also be using some other credential (it attempts multiple credentials like VisualStudioCredential before the AzureCliCredential).
You could instead try to use AzureCliCredential directly and see if it works.
That of course won't use Managed Identity so you'd need to use ChainedTokenCredential with the AZ CLI credential + ManagedIdentityCredential to support both.
I am trying to get the access token of the service principal using the following code.
$authUrl = "https://login.windows.net/" + $tenantid + "/oauth2/token/"
$body = #{
grant_type = "client_credentials"
client_id = $serviceprincipalid
resource = "https://management.azure.com/"
client_secret = $serviceprincipalkey
};
$response = Invoke-RestMethod –Uri $authUrl –Method POST –Body $body
Write-Host $response
Write-Output $response.access_token
##vso[task.setvariable variable=myToken;]$response.access_token
The above code is working perfectly at my local machine's PowerShell but it is giving the following error when I am running the same code base in the Azure DevOps pipeline.
ClientSecretCredential authentication failed: A configuration issue is preventing
authentication - check the error message from the server for details. You can modify the
configuration in the application registration portal. See https://aka.ms/msal-net-invalid-
client for details. Original exception: AADSTS7000222: The provided client secret keys are
expired. Visit the Azure Portal to create new keys for your app, or consider using certificate
credentials for added security: https://learn.microsoft.com/azure/active-
directory/develop/active-directory-certificate-credentials
Trace ID: 98787ui7-e8ae-4712-b8b5-7678u8765rt5
Correlation ID: yhjnbv43-56sy-9ksy-b8b5-mj876yu78i90
Timestamp: 2021-03-16 12:32:28Z
There was an error with the service principal used for the deployment.`
I checked the secret keys, but the secret keys not expired, it's expiry date is already set for the year 2022. And if it would expire then the code should not have worked at my local machine's PowerShell.
Does anyone have any idea? please let me know to resolve this issue.
Well, actually the error was not caused by the script above, per my test, it works fine in devops.
If you use the Azure PowerShell task, it will let you configure a service connection to use, when you run the task, it will connect Azure powershell with the service principal configured in the service connection automatically. The error was caused by the expired secret of the service principal configured in the service connection, not the one in your script.
I can also reproduce your issue on my side.
To solve this issue, please follow the steps below.
1.Navigate to the Azure PowerShell task, check which service connection you used.
2.Navigate to the Project Settings in devops -> Service connections -> find the one you used -> click it -> Manage Service Principal.
Then it will open the related AD App page, just create a new secret and service connection, use it in the Azure Powershell task, follow the same steps I have mentioned here.
3.After configuration, test it again, it will work fine.
I am trying to build a VSTS extension that can communicate to azure web app. I was able to achieve this but without authentication. I was referring to the Microsoft documentation.
I took the token generated from browser i.e console.log(token) and verified it in this website.
It says Invalid signature.
The logic mentioned for .Net framework to validate the generated token does not work. It gives me following error:
IDX10500: Signature validation failed. Unable to resolve
SecurityKeyIdentifier: 'SecurityKeyIdentifier
(
IsReadOnly = False,
Count = 1,
Clause[0] = X509ThumbprintKeyIdentifierClause(Hash = 0xA0EBDCCF933FEE9F878C82A5157CFDDEEFD5D19A)
)
',
token: '{"typ":"JWT","alg":"RS256",......
Replace VSS.getAccessToken() to VSS.getAppToken() can solve the issue.
The authentication used to work for us earlier but has stopped suddenly.
We have an app built in Xamamin iOs and have registered the application in Azure AD account, provided the ClientID and redirect URL as specified. But it throws an error when "authContext.AcquireToken" is being called
Exception: Microsoft.IdentityModel.Clients.ActiveDirectory.AdalServiceException: AADSTS65005: The client application has requested access to resource 'example.com/'. This request has failed because the client has not specified this resource in its requiredResourceAccess list.
Trace ID: ea22c27c-9913-4423-92dc-6fff1cf9904d
Correlation ID: 4c19258b-2391-4585-911e-853157dde073
Timestamp: 2017-01-24 09:28:49Z
Code we are using to acquire token:
var authContext = new AuthenticationContext(authority);
if (authContext.TokenCache.ReadItems().Any())
authContext = new AuthenticationContext(authContext.TokenCache.ReadItems().First().Authority);
var authResult = await authContext.AcquireTokenAsync(resource, clientId, new Uri(returnUri),
new PlatformParameters(UIApplication.SharedApplication.KeyWindow.RootViewController));
And for authority variable, we are using "https://login.microsoftonline.com/common" to authenticate. We also tried "https://login.windows.net/common" but with no luck.
Has there been any microsoft updates lately which could have stopped this code from running?
Based on the error message, you were trying to access the resource example.com/.
However this resource was removed to grant to that app.
To fix this issue, you can login the Azure portal to grant this resource to your app again like figure below(switch your Azure AD->App registrations->You App->Settings->Required permissions->Add):