Azure Data Lake Service-to-service authentication client secret, AdalServiceException and WebException - c#

Tyring to use the below docs to get this up and running for my console app that I plan to port to Azure Functions. https://learn.microsoft.com/en-us/azure/data-lake-store/data-lake-store-get-started-net-sdk
The code below is where I'm getting stuck
CODE SNIP
// Service principal / appplication authentication with client secret / key
// Use the client ID of an existing AAD "Web App" application.
SynchronizationContext.SetSynchronizationContext(new SynchronizationContext());
var domain = "<AAD-directory-domain>";
var webApp_clientId = "<AAD-application-clientid>";
var clientSecret = "<AAD-application-client-secret>";
var clientCredential = new ClientCredential(webApp_clientId, clientSecret);
var creds = await ApplicationTokenProvider.LoginSilentAsync(domain, clientCredential);
MY IMPLEMENTATION
SynchronizationContext.SetSynchronizationContext(new SynchronizationContext());
var domain = "https://microsoft.onmicrosoft.com";
var webApp_clientId = "<my-client-id>";
var clientSecret = "<my-client-secret>";
var clientCredential = new ClientCredential(webApp_clientId, clientSecret);
var creds = await ApplicationTokenProvider.LoginSilentAsync(domain, clientCredential);
SynchronizationContext.SetSynchronizationContext(new SynchronizationContext());
_adlsClient = new DataLakeStoreAccountManagementClient(creds) { SubscriptionId = _subId };
_adlsFileSystemClient = new DataLakeStoreFileSystemManagementClient(creds);
await _adlsFileSystemClient.FileSystem.MkdirsAsync("<name-of-my-dlstore>", "tempdir");
I also made sure to give my app permissions to my specified folder in Azure Data Lake instance:
I also made sure to give all child folders in this directory the same level or permissions:
Assigned permissions to file path
When I run my implementation I get the below errors. Any advice SO?
System.AggregateException: 'One or more errors occurred.'
Inner Exception 1
AdalServiceException: AADSTS90002: Requested tenant identifier 'https:' is not valid.
Trace ID: d1718b0a-0533-4708-a311-4e1622840100
Correlation ID: a1544df2-692e-43d2-8acf-25a847956fb6
Timestamp: 2017-03-29 01:30:18Z
Inner Exception 2
WebException: The remote server returned an error: (400) Bad Request.
AS PART OF SOLUTION
Need to make sure to give root folder read, write, execute permissions, (this will trickle down to the one folder you want to give these permissions for) then remove those permissions from all other folders you don't want these permissions assigned too, making sure you select the option to remove these permissions for that sub folder and all it's kiddos/children.

AdalServiceException: AADSTS90002: Requested tenant identifier 'https:' is not valid.
That is your tenant name ,like "microsoft.onmicrosoft.com" .
WebException: The remote server returned an error: (400) Bad Request.
What is the detail error message , please refer to tutorial :
https://learn.microsoft.com/en-us/azure/data-lake-store/data-lake-store-get-started-net-sdk
I followed the detail steps to use service-to-service authentication with client secret , and successfully create a directory . Code below is for your reference :
public static async Task CreateDirectory()
{
SynchronizationContext.SetSynchronizationContext(new SynchronizationContext());
var domain = "microsoft.onmicrosoft.com";
var webApp_clientId = "client id";
var clientSecret = "client secret";
var clientCredential = new ClientCredential(webApp_clientId, clientSecret);
var creds = ApplicationTokenProvider.LoginSilentAsync(domain, clientCredential).Result;
SynchronizationContext.SetSynchronizationContext(new SynchronizationContext());
_adlsClient = new DataLakeStoreAccountManagementClient(creds) { SubscriptionId = "_subId" };
_adlsFileSystemClient = new DataLakeStoreFileSystemManagementClient(creds);
await _adlsFileSystemClient.FileSystem.MkdirsAsync("_adlsAccountName", "tempdir");
}
static void Main(string[] args)
{
CreateDirectory().Wait();
}
EDIT
You need to assign Execute permission to your app if you want to create a directory . Tenant ID and tenant name are both available ,means :
var domain = "microsoft.onmicrosoft.com";
//you could also use tenant id
var domain = "Your tenant ID";

Related

Code: BadRequest Message: /me request is only valid with delegated authentication flow

I am trying to upload file on onedrive by using microsoft graph onedrive api.
I am using the method for authentication
Client credentials provider
https://learn.microsoft.com/en-us/graph/sdks/choose-authentication-providers?tabs=CS#client-credentials-provider
Like:
// /.default scope, and preconfigure your permissions on the
// app registration in Azure. An administrator must grant consent
// to those permissions beforehand.
var scopes = new[] { "https://graph.microsoft.com/.default" };
// Multi-tenant apps can use "common",
// single-tenant apps must use the tenant ID from the Azure portal
var tenantId = "my-tenantid";
// Values from app registration
var clientId = "YOUR_CLIENT_ID";
var clientSecret = "YOUR_CLIENT_SECRET";
// using Azure.Identity;
var options = new TokenCredentialOptions
{
AuthorityHost = AzureAuthorityHosts.AzurePublicCloud
};
// https://learn.microsoft.com/dotnet/api/azure.identity.clientsecretcredential
var clientSecretCredential = new ClientSecretCredential(
tenantId, clientId, clientSecret, options);
var graphClient = new GraphServiceClient(clientSecretCredential, scopes);
HttpPostedFileBase file = Request.Files;[0];
int fileSize = file.ContentLength;
string fileName = file.FileName;
string mimeType = file.ContentType;
Stream fileContent = file.InputStream;
var res = await graphClient.Me.Drive.Root.ItemWithPath(fileName).Content
.Request()
.PutAsync<DriveItem>(fileContent);
After executing this code then it gives an error in response.
Message: /me request is only valid with delegated authentication flow.
Inner error:
AdditionalData:
date: 2021-12-29T05:30:08
request-id: b51e50ea-4a62-4dc7-b8d2-b26d75268cdc
client-request-id: b51e50ea-4a62-4dc7-b8d2-b26d75268cdc
ClientRequestId: b51e50ea-4a62-4dc7-b8d2-b26d75268cdc
Client credential flow will generate the token on behalf the app itself, so in this scenario, users don't need to sign in first to generate the token stand for the user and then call the api. And because of the design,when you used Me in the graph SDK, your code/app don't know who is Me so it can't work. You should know the user_id first and use /users/{id | userPrincipalName} instead of /Me, in the SDK, that is graphClient.Users["your_user_id"] instead of graphClient.Me
In your scenario, there're 2 solutions, one way is using delegated authentication flow like what you said in your title, another way is get the user id before calling the graph api so that you can use Users["id"] but not Me
===================== Update=========================
I haven't finished the code yet but I found the correct solution now.
Firstly, we can upload file to one drive by this api, you may check the screenshot if this is one drive or sharepoint:
https://graph.microsoft.com/v1.0/users/user_id/drive/items/root:/testupload2.txt:/content
If it is, then the next is easy, using the code below to get an access token and send http request to calling the api:
var scopes = new[] { "https://graph.microsoft.com/.default" };
var tenantId = "tenant_name.onmicrosoft.com";
var clientId = "your_azuread_clientid";
var clientSecret = "corresponding_client_secret";
var clientSecretCredential = new ClientSecretCredential(
tenantId, clientId, clientSecret);
var tokenRequestContext = new TokenRequestContext(scopes);
var token = clientSecretCredential.GetTokenAsync(tokenRequestContext).Result.Token;
I know it's complex because the api is not the same as this one which has SDK sample, but I think it also deserves to try if they are similar.

Unable to authorize Azure LogAnalytics Workspace

I am trying to connect to my workspace in the Azure Portal. I am getting the error as
Operation returned an invalid status code 'Unauthorized'.
The creds object has fetched the Authentication Token and I have added resource permissions to my app as mentioned in this link
using System;
using Microsoft.Azure.OperationalInsights;
using Microsoft.Rest.Azure.Authentication;
namespace LogAnalytics
{
class Program
{
static void Main(string[] args)
{
var workspaceId = "**myworkspaceId**";
var clientId = "**myClientId**";
var clientSecret = "**myClientSecret**";
//<your AAD domain>
var domain = "**myDomain**";
var authEndpoint = "https://login.microsoftonline.com";
var tokenAudience = "https://api.loganalytics.io/";
var adSettings = new ActiveDirectoryServiceSettings
{
AuthenticationEndpoint = new Uri(authEndpoint),
TokenAudience = new Uri(tokenAudience),
ValidateAuthority = true
};
var creds = ApplicationTokenProvider.LoginSilentAsync(domain,clientId, clientSecret,
strong textadSettings).GetAwaiter().GetResult();
var client = new OperationalInsightsDataClient(creds);
client.WorkspaceId = workspaceId;
//Error happens below
var results = client.Query("union * | take 5");
Console.WriteLine(results);
Console.ReadLine();
}
}
}
Operation returned an invalid status code 'Unauthorized'.
According to the error message and the code you provided, you need to add permission in your registered application in Azure AD.
Note: If you want to add permission to application you need to be admin, and then you could use the ClientId and ClientSecret to get Authentication Token and read log analytics.
However, if you are not admin, you could delegate permission to user and access to Azure AD with username and password.
To get authentication token with user, you could can use the function UserTokenProvider.LoginSilentAsync(nativeClientAppClientid, domainName, userName, password).GetAwaiter().GetResult() to get our credentials.

Azure linked services with data factory custom activity

Can't able to create linked services using Azure data factory (ADF),
I have read/write permission for linked services at ADF level.
using Microsoft.Azure.Management.ResourceManager;
using Microsoft.Azure.Management.DataFactory;
using Microsoft.Azure.Management.DataFactory.Models;
using Microsoft.IdentityModel.Clients.ActiveDirectory;
LinkedServiceResource storageLinkedService = new
LinkedServiceResource(
new AzureStorageLinkedService
{
ConnectionString = new
SecureString("DefaultEndpointsProtocol=https;AccountName=" +
storageAccount + ";AccountKey=" + storageKey)
}
);
client.LinkedServices.CreateOrUpdate(resourceGroup,
dataFactoryName, storageLinkedServiceName, storageLinkedService);
BTW I used both client credential as well as user credential
ClientCredential cc = new ClientCredential(applicationId,
authenticationKey);
var cc = new UserPasswordCredential(userName, password);
Error Response for using Client credential:
Microsoft.Azure.Management.DataFactory.Models.ErrorResponseException:
Operation returned an invalid status code 'Forbidden'
at Microsoft.Azure.Management.DataFactory.LinkedServicesOperations.
<CreateOrUpdateWithHttpMessagesAsync>d__6.MoveNext() --- End of stack
trace from previous location where exception was thrown ---
Error Response for using User credential:
System.Net.Http.HttpRequestException: Response status code does not
indicate success: 401 (Unauthorized). --->
Microsoft.IdentityModel.Clients.ActiveDirectory.AdalException:
{"error":"invalid_client","error_description":"AADSTS70002: The
request body must contain the following parameter: 'client_secret or
client_assertion'.\r\nTrace ID: 2264d637-8786-4a40-96d4-
5d27b0670300\r\nCorrelation ID: fec688c8-bb92-49c2-86d3-
1e091181fe10\r\nTimestamp: 2017-11-29 05:30:23Z","error_codes":
[70002],"timestamp":"2017-11-29 05:30:23Z","trace_id":"2264d637-8786-
4a40-96d4-5d27b0670300","correlation_id":"fec688c8-bb92-49c2-86d3-
1e091181fe10"}: Unknown error
--- End of inner exception stack trace ---
Accoring to your exception, it seems that you use the resource owner flow from a a web client. A confidential client, such as a web App client, cannot use direct user credentials.
You would need to invoke it as a public client (native client app), not as a confidential client (web app/API). Please refer to this document for more about how to use ADAL,especially the Constraints & Limitations section
No web sites/confidential clients
This is not an ADAL limitation, but an AAD setting. You can only use those flows from a native client. A confidential client, such as a web site, cannot use direct user credentials.
To access resources in your subscription, you need to assign role to the registried App.
Please have a try to use the following to get TokenCredentials, The following is the demo code to create inked services. It works correctly on my side. We also could refer to this document.
private static async Task<string> GetToken(string tenantId, string clientId, string secretKey)
{
var context = new AuthenticationContext("https://login.windows.net/" + tenantId);
ClientCredential clientCredential = new ClientCredential(clientId, secretKey);
var tokenResponse = await context.AcquireTokenAsync("https://management.azure.com/", clientCredential);
var accessToken = tokenResponse.AccessToken;
return accessToken;
}
var token = GetToken(_tenantId, _clientId, _screctKey).Result;
TokenCredentials credentials = new TokenCredentials(token);
DataFactoryManagementClient client = new
DataFactoryManagementClient(credentials) { SubscriptionId = subscriptionId };
DataFactoryManagementClient client = new DataFactoryManagementClient(credentials) { SubscriptionId = subscriptionId };
LinkedServiceResource storageLinkedService = new LinkedServiceResource(new AzureStorageLinkedService{
ConnectionString = new SecureString("DefaultEndpointsProtocol=https;AccountName=" + storageAccount + ";AccountKey=" + storageKey)});
var result =client.LinkedServices.CreateOrUpdateWithHttpMessagesAsync(resourceGroup, factoryName, storageLinkedServiceName, storageLinkedService).Result;

How to get On-Behalf-Of-User token in .NET using ADAL

I have created an Azure AAD app of type webapp which has client secret and redirect url. Now, I want to get an access token on behalf of user using the AAD app. From looking at the documentation, I got the following code so far.
static void Main(string[] args)
{
var clientId = "<REDACTED>";
var clientSecret = "<REDACTED>";
var resourceAppIdURI = "https://api.office.com/discovery/";
var authority = "https://login.microsoftonline.com/common";
AuthenticationContext ac = new AuthenticationContext(authority, new FileCache());
ClientCredential cc = new ClientCredential(clientId, clientSecret);
// Get token as application
var task = ac.AcquireTokenAsync(resourceAppIdURI, cc);
task.Wait();
var appToken = task.Result.AccessToken;
// Get tokenn on behalf of user
UserCredential uc = new UserCredential("usrname#mytenant.com");
task = ac.AcquireTokenAsync(resourceAppIdURI, clientId, uc);
var userToken = task.Result.AccessToken;
Console.ReadLine();
}
But this is the error I get when I try to get user token is as follows.
Message "AADSTS70002: The request body must contain the following
parameter: 'client_secret or client_assertion'.\r\nTrace ID:
0e977f67-d5cb-4cf5-8fea-bac04b6d0400\r\nCorrelation ID:
824a96bf-8007-4879-970c-2680644b8669\r\nTimestamp: 2017-07-21
05:02:41Z" string
Why am I getting this error and how to fix it?
Do I need to login with the user first and then use UserAssertion instead ?
There are tonnes of overloaded methods for AcquireTokenAsync method, but not sure what I should use.
I also looked at this github url to see how they are doing it
https://github.com/Azure-Samples/active-directory-dotnet-webapi-onbehalfof/blob/8afb3e6a648d8e7246685bf6747d009006c761b8/TodoListService/Controllers/TodoListController.cs
This is the relevant code to get token as logged in user
ClientCredential clientCred = new ClientCredential(clientId, appKey);
var bootstrapContext = ClaimsPrincipal.Current.Identities.First().BootstrapContext as System.IdentityModel.Tokens.BootstrapContext;
string userName = ClaimsPrincipal.Current.FindFirst(ClaimTypes.Upn) != null ? ClaimsPrincipal.Current.FindFirst(ClaimTypes.Upn).Value : ClaimsPrincipal.Current.FindFirst(ClaimTypes.Email).Value;
string userAccessToken = bootstrapContext.Token;
UserAssertion userAssertion = new UserAssertion(bootstrapContext.Token, "urn:ietf:params:oauth:grant-type:jwt-bearer", userName);
string authority = String.Format(CultureInfo.InvariantCulture, aadInstance, tenant);
string userId = ClaimsPrincipal.Current.FindFirst(ClaimTypes.NameIdentifier).Value;
AuthenticationContext authContext = new AuthenticationContext(authority, new DbTokenCache(userId));
Here they already have a logged in user and creating a UserAssertion from that loggedin user's token. In my console app, the user hasn't logged in yet.
So I need a way to do this in my console app. How can I show the AAD login page to the user as a pop-up and then once the user enters creds use that info to create an UserAssertion object?
thanks
Your scenario is a native application that calls a web API on behalf of a user . The native application could obtains an access token for the user by using the OAuth 2.0 authorization code grant , then access token is then sent in the request to the web API, which authorizes the user and returns the desired resource :
Please read more about the description of protocol flow here .Also see the code samples for Native Application to Web API scenarios.
In addition , you could click here for code sample about how to call the Azure AD Graph API from a native client(.net console application ) ,it uses the Active Directory Authentication Library (ADAL) for authentication .

B2B access in multi tenant application

I have succesfully setup a multi tenant application.
For now, I am able to authenticate the user and use tokens to access other resources. (Microsoft Graph & Microsoft AD Graph)
Now I want to get B2B working.
Current flow:
- User signs in
- AuthorizationCodeReceived gets the acquires the token (via $commonAuthority endpoint)
- When requesting a token for the Ad Graph, I am using the $tenantAuthority
This works perfectly when $tenantAuthority is the same tenant authority as the one where the account was created in.
However, if I login with another user (from another tenant, given trust to the actual tenant) and use $tenantAuthority = trusted authority, then I always the following error:
Failed the refresh token:
AADSTS65001: The user or administrator has not consented to use the application with ID
If I change $tenantAuthority to the 'source' tenant authority where the user was created in, everything works fine.
Any help would be greatly appreciated.
Update: Code sample
App has two tenants (tenantA en tenantB) and I will use a user from tenantB with tenantA given a trust to this user.
AuthorizationCodeReceived = async context =>
{
TenantContext.TenantId = "someguid";
var tenantId =
TenantContext.TenantId;
// get token cache via func, because the userid is only known at runtime
var getTokenCache = container.Resolve<Func<string, TokenCache>>();
var userId = context.AuthenticationTicket.Identity.FindFirst(ClaimTypes.ObjectIdentifier).Value;
var tokenCache = getTokenCache(userId);
var authenticationContext = new AuthenticationContext($"{configuration.Authority}",
tokenCache);
await authenticationContext.AcquireTokenByAuthorizationCodeAsync(
context.Code,
new Uri(context.Request.Uri.GetLeftPart(UriPartial.Authority)),
new ClientCredential(configuration.ClientId, configuration.ClientSecret),
configuration.GraphResourceId);
}
This code works perfectly. Login in with a user from both tenants works perfectly.
But when I need the Graph Service Client or ActiveDirectoryClient, I need to obtain access tokens to been able to address an api for a certain tenant. I retrieve the access tokens like this:
public IGraphServiceClient CreateGraphServiceClient()
{
var client = new GraphServiceClient(
new DelegateAuthenticationProvider(
async requestMessage =>
{
Logger.Debug("Retrieving authentication token to use in Microsoft Graph.");
string token;
var currentUserHomeTenantId = TenantContext.TenantId;
var currentUserObjectId = ClaimsPrincipal.Current.FindFirst(ClaimTypes.ObjectIdentifier).Value;
var authenticationContext =
new AuthenticationContext($"{_configuration.TenantAuthorityPrefix}{currentUserHomeTenantId}",
_tokenCacheFactoryMethod(currentUserObjectId));
var clientCredential = new ClientCredential(_configuration.ClientId, _configuration.ClientSecret);
try
{
token = await GetTokenSilently(authenticationContext, _configuration.GraphResourceId, currentUserObjectId);
}
catch (AdalSilentTokenAcquisitionException e)
{
Logger.Error("Failed to retrieve authentication token silently, trying to refresh the token.", e);
var result = await authenticationContext.AcquireTokenAsync(_configuration.GraphResourceId, clientCredential);
token = result.AccessToken;
}
requestMessage.Headers.Authorization = new AuthenticationHeaderValue(AuthenticationHeaderKeys.Bearer, token);
}));
return client;
}
public IActiveDirectoryClient CreateAdClient()
{
var currentUserHomeTenantId = TenantContext.TenantId;
var currentUserObjectId = ClaimsPrincipal.Current.FindFirst(ClaimTypes.ObjectIdentifier).Value;
var graphServiceUrl = $"{_configuration.AdGraphResourceId}/{currentUserHomeTenantId}";
var tokenCache = _tokenCacheFactoryMethod(currentUserObjectId);
var client = new ActiveDirectoryClient(new Uri(graphServiceUrl),
() => GetTokenSilently(
new AuthenticationContext(
$"{_configuration.TenantAuthorityPrefix}{ClaimsPrincipal.Current.FindFirst(ClaimTypes.TenantId).Value}", tokenCache
),
_configuration.AdGraphResourceId, currentUserObjectId
));
return client;
}
When I do a request with one of the two client SDK's, I got the following error:
Failed the refresh token: AADSTS65001: The user or administrator has not consented to use the application with ID.
Changing the catch method when retrieving the Token did the trick:
if(e.ErrorCode == "failed_to_acquire_token_silently")
{
HttpContext.Current.Response.Redirect(authenticationContext.GetAuthorizationRequestUrlAsync(resourceId, _configuration.ClientId, new Uri(currentUrl),
new UserIdentifier(currentUserId, UserIdentifierType.UniqueId), string.Empty);
}
I don't see that you mention that so: in a B2B collaboration you've to invite user from other tenant first. The steps are like that:
invite and authorize a set of external users by uploading a comma-separated values - CSV file
Invitation will be send to external users.
The invited user will either sign in to an existing work account with Microsoft (managed in Azure AD), or get a new work account in Azure AD.
After signed in, user will be redirected to the app that was shared with them
That works perfectly in my case.
Regarding some problems which I've detect:
Trailing "/" at the end of the active directory resource - try to remove it as this may cause problems. Bellow you will find some code to get authentication headers:
string aadTenant = WebServiceClientConfiguration.Settings.ActiveDirectoryTenant;
string clientAppId = WebServiceClientConfiguration.Settings.ClientAppId;
string clientKey = WebServiceClientConfiguration.Settings.ClientKey;
string aadResource = WebServiceClientConfiguration.Settings.ActiveDirectoryResource;
AuthenticationContext authenticationContext = new AuthenticationContext(aadTenant);
ClientCredential clientCredential = new ClientCredential(clientAppId, clientKey);
UserPasswordCredential upc = new UserPasswordCredential(WebServiceClientConfiguration.Settings.UserName, WebServiceClientConfiguration.Settings.Password);
AuthenticationResult authenticationResult = await authenticationContext.AcquireTokenAsync(aadResource, clientAppId, upc);
return authenticationResult.CreateAuthorizationHeader();
Applications provisioned in Azure AD are not enabled to use the OAuth2 implicit grant by default. You need to explicitly opt in - more details can be found here: Azure AD OAuth2 implicit grant

Categories

Resources