Azure invalid AccessToken - c#

i am trying to use Microsoft.Azure.Management.Resources library to manage some Azure resources. I have registered app in Azure AD and i gave it all permissons. I took its ApplicationId and Secret + TennantId and SubscriptionId and tried to obtaion AccessToken like this:
var clientCredential = new ClientCredential(_model.DeploymentDetails.CliendId, _model.DeploymentDetails.ClientSecret);
var context = new AuthenticationContext("https://login.windows.net/"+model.DeploymentDetails.TennantId);
_accessToken = context.AcquireTokenAsync("https://management.azure.com/", clientCredential).Result.AccessToken;
_resourceManagementClient = new ResourceManagementClient(new TokenCloudCredentials(_model.DeploymentDetails.SubscriptionId,_accessToken));
I get some AccessToken. BUT when i try to use it like this:
var x = _resourceManagementClient.ResourceGroups.List(...);
I get this error:
Additional information: InvalidAuthenticationToken: The received access token is not valid: at least one of the claims 'puid' or 'altsecid' or 'oid' should be present. If you are accessing as application please make sure service principal is properly created in the tenant.
Any ideas?
Thank you very much.

As far as I know, Microsoft.Azure.Management.Resources.dll that implements the ARM API. We need to assign application to role, after that then we can use token in common. More information about how to assign application to role please refer to the article .This blog also has more detail steps to get AceessToken.

Related

Authenticate Azure AD using Provided Access Token

I tried to find an Azure authentication mechanism that uses an access token as a parameter. but no luck. I just found ClientSecretCredential class that use tenant id, client id, and client secret as a parameter like below :
var clientSecretCredential = new ClientSecretCredential(tenantId, clientId, clientSecret);
the reason I need the that is the access token will be generated by another service and my service will only accept access token to be used to authenticate Azure AD.
Actually, I can utilize Azure Management RestAPI to do that. However to improve developer experience I'd like to utilize .NET client library if possible.
I have tried to find documentation in Azure Identity client library in https://learn.microsoft.com/en-us/dotnet/api/overview/azure/identity-readme?view=azure-dotnet, but I couldn't find any class or method that I need.
If you want tokens from azure ad you can use using Microsoft.IdentityModel.Clients.ActiveDirectory; library to get the tokens.
I am assuming that you have already created an azure ad app registration and already possess the client_id , client_secret and tenant_id. Just save this as strings in code.
Now we can use the clientcredential along with authenticationContext we can acquire tokens.
Complete program :
string client_id = "";
string client_secret = "";
string tenant_id = "";
string endpoint = "https://login.microsoftonline.com/"+tenant_id;
ClientCredential credent = new ClientCredential(client_id , client_secret);
var context = new AuthenticationContext(endpoint);
var result = context.AcquireTokenAsync("https://management.azure.com/",credent);
var result = context.AcquireTokenAsync("https://management.azure.com/",credent);
Console.WriteLine(result.Result.AccessToken);
Here result.Result.AccessToken will give you a access token in form of a token.

Body must contain client_secret or client_assertion

I registered new application as Web app / API (not native), added permission to Access Dynamics 365 as organization users.
I following this guide (https://code.msdn.microsoft.com/simple-web-api-quick-start-e0ba3d6b) which has the below code, the only difference is that I have updated my Microsoft.IdentityModel.Clients.ActiveDirectory library which required small code change.
//Obtain the Azure Active Directory Authentication Library (ADAL)
AuthenticationParameters ap = AuthenticationParameters.CreateFromResourceUrlAsync(new Uri(serviceUrl + "api/data/")).Result;
AuthenticationContext authContext = new AuthenticationContext(ap.Authority, false);
//Note that an Azure AD access token has finite lifetime, default expiration is 60 minutes.
AuthenticationResult authResult = authContext.AcquireTokenAsync(
serviceUrl, clientId, new Uri(redirectUrl),
new PlatformParameters(PromptBehavior.Always)).Result;
When I run this I getting a popup where I fill in my credentials and then it throws this error:
AdalException: {"error":"invalid_client","error_description":"AADSTS70002: The request body must contain the following parameter: 'client_secret or client_assertion'.\r\nTrace ID: xxx\r\nCorrelation ID: xxx\r\nTimestamp: 2018-06-28 10:17:20Z","error_codes":[70002],"timestamp":"2018-06-28 10:17:20Z","trace_id":"xxx","correlation_id":"xxx"}: Unknown error
I tried to add the client_secret by applying the change below but it still doesn't work
AuthenticationResult authResult = authContext.AcquireTokenAsync(
serviceUrl, clientId, new Uri(redirectUrl),
new PlatformParameters(PromptBehavior.Always), UserIdentifier.AnyUser,
$"client_secret={clientSecret}").Result;
But when I run this it does work, but this is not what I want, I want to login with specific user.
AuthenticationResult authResult = authContext.AcquireTokenAsync(
serviceUrl, new ClientCredential(clientId, clientSecret)).Result;
The Client Credential and Client Assertion authentication flows are meant for service to service communication, without user involvement. So your Web Api would access Dynamics not in the context of a user, but as itself.
Have a look at the official wiki to understand more: https://github.com/AzureAD/azure-activedirectory-library-for-dotnet/wiki/Client-credential-flows
Also, please be aware that we cannot help you if you make changes to Microsoft.IdentityModel.Clients.ActiveDirectory. You'd also miss out on updates, some of which are security critical. But feel free to propose changes if you think others would benefit!

Error when using AD to work with Azure Management API

I'm using Microsoft.WindowsAzure.Management and Microsoft.IdentityModel.Clients.ActiveDirectory packages trying to work with Azure Management API from C# code, but when I try to retrieve some data from it, I'm always getting the error:
ForbiddenError: The server failed to authenticate the request. Verify that the certificate is valid and is associated with this subscription.
There's the code sample I'm using:
using Microsoft.IdentityModel.Clients.ActiveDirectory;
using Microsoft.WindowsAzure.Management;
var authContext = new Microsoft.IdentityModel.Clients.ActiveDirectory.AuthenticationContext("https://login.windows.net/mytenant");
var cc = new Microsoft.IdentityModel.Clients.ActiveDirectory.ClientCredential("azure-app-id", "azure-app-secret");
var token = await authContext.AcquireTokenAsync("https://management.core.windows.net/", cc);
var tokenCred = new Microsoft.Azure.TokenCloudCredentials(token.AccessToken);
var client = new ManagementClient(tokenCred);
// this is where I get the error:
var subscriptions = await client.Subscriptions.GetAsync(CancellationToken.None);
I believe you're getting this error is because the Service Principal (or in other words the Azure AD application) does not have permission on your Azure Subscription. You would need to assign a role to this Service Principal.
Please see this link regarding how you can assign a role in an Azure Subscription to a Service Principal: https://learn.microsoft.com/en-us/azure/azure-resource-manager/resource-group-create-service-principal-portal#assign-application-to-role.
Once you do that, the error should go away.
I can reproduce this issue too. And to list the subscription, we need to use the SubscriptionClient instead of ManagementClient. Here is the code which works well for me:
var token = "";
var tokenCred = new Microsoft.Azure.TokenCloudCredentials(token);
var subscriptionClient = new SubscriptionClient(tokenCred);
foreach (var subscription in subscriptionClient.Subscriptions.List())
{
Console.WriteLine(subscription.SubscriptionName);
}
Note:To make the code work, we need to acquire token using the owner of the subscription instead of the certificate.

azure data lake authorization

I am new to Azure Data Lake Analytics and am converting a C# batch job to use service to service authentication before submitting stored procedures to Azure Data Lake Analytics.
public void AuthenticateADLUser()
{
//Connect to ADL
// Service principal / appplication authentication with client secret / key
SynchronizationContext.SetSynchronizationContext(new SynchronizationContext());
cTokenCreds = ApplicationTokenProvider.LoginSilentAsync(strDomain, strWebApp_clientId, strClientSecret).Result;
SetupClients(cTokenCreds, strSubscriptionID);
}
public static void SetupClients(ServiceClientCredentials tokenCreds, string subscriptionId)
{
_adlaClient = new DataLakeAnalyticsAccountManagementClient(tokenCreds);
_adlaClient.SubscriptionId = subscriptionId;
_adlaJobClient = new DataLakeAnalyticsJobManagementClient(tokenCreds);
_adlsFileSystemClient = new DataLakeStoreFileSystemManagementClient(tokenCreds);
}
Even though I have given it the correct ClientId the error comes back with a different ClientID in the error when I execute the following code:
var jobInfo = _adlaJobClient.Job.Create(_adlsAccountName, jobId, parameters);.
The error message is:
The client 'e83bb777-f3af-4526-ae34-f5461a5fde1c' with object id 'e83bb777-f3af-4526-ae34-f5461a5fde1c' does not have authorization to perform action 'Microsoft.Authorization/permissions/read' over scope '/subscriptions/a0fb08ca-a074-489c-bed0-....
Why is the ClientID different than the one I used in the code?
Is this a code issue or a permissions issue? I assume that it is code since the ClientID is not an authorized one that I created.
note: The SubscriptionId is correct.
I assumed you created an Azure Active Directory App and are you the client and domain IDs of this app. If not, you'll need that... If you do have that, then can you check if the App has permissions over your Data Lake Store: https://learn.microsoft.com/en-us/azure/data-lake-store/data-lake-store-authenticate-using-active-directory
Had exactly same symptoms. WebApp was created in AAD in portal originally to access Azure Data Lake Store and same code-snippet worked perfectly. When I decided to re-use same WebApp (clientid/secret) it failed with same error, even though I have given reader/contributor roles on sub/RG/ADLA to the App.
I think the reason is that WebApp underneath has a "service principal" object (thus error msg shows different object id) and ADLA uses it for some reason. Mine didn't have credentials set - empty result:
Get-AzureRmADSpCredential -objectid <object_id_from_error_msg>
Added new password as described here
New-AzureRmADSpCredential -objectid <object_id_from_error_msg> -password $password
Used the pwd as secret in LoginSilentAsync, clientId was left as before - WebApp clientId (not the principal object id shown in the error)
I wasn't able to find this principal info in portal, only PS.

Get user email info from a Dotnet Google API

I'm have working two separate implementations of Oauth2 for both the gData and the Drive C# APIs, storing token information in an OAuth2Parameters and AuthorizationState respectively. I'm able to refresh the token and use them for the necessary API calls. I'm looking for a way to use this to get the user's information, mainly the email address or domain.
I tried following the demo for Retrieve OAuth 2.0 Credentials but I'm getting a compile error similar to rapsalands' issue here, saying it
can't convert from
'Google.Apis.Authentication.OAuth2.OAuth2Authenticator<
Google.Apis.Authenticatio‌​n.OAuth2.DotNetOpenAuth.NativeApplicationClient>'
to 'Google.Apis.Services.BaseClientService.Initializer'.
I just grabbed the most recent version of the Oauth2 api dlls so I don't think that's it.
All the other code samples I'm seeing around mention using the UserInfo API, but I can't find any kind of C#/dotnet api that I can use with it without simply doing straight GET/POST requests.
Is there a way to get this info using the tokens I already have with one of the C# apis without making a new HTTP request?
You need to use Oauth2Service to retrieve information about the user.
Oauth2Service userInfoService = new Oauth2Service(credentials);
Userinfo userInfo = userInfoService.Userinfo.Get().Fetch();
Oauth2Service is available on the following library: https://code.google.com/p/google-api-dotnet-client/wiki/APIs#Google_OAuth2_API
For #user990635's question above. Though the question is a little dated, the following may help someone. The code uses Google.Apis.Auth.OAuth2 version
var credentials =
await GoogleWebAuthorizationBroker.AuthorizeAsync(
new ClientSecrets {ClientId = clientID, ClientSecret = clientSecret},
new[] {"openid", "email"}, "user", CancellationToken.None);
if (credentials != null)
{
var oauthSerivce =
new Oauth2Service(new BaseClientService.Initializer {HttpClientInitializer = credentials});
UserInfo = await oauthSerivce.Userinfo.Get().ExecuteAsync();
}

Categories

Resources