Reputation: 1591
I want to call graph api, https://graph.windows.net for that I am using a delegated permission as below for token
UserPasswordCredential credentials = new UserPasswordCredential("username", "password");
AuthenticationContext authContext = new AuthenticationContext(string.Format("https://login.windows.net/{0}", "mytenant.onmicrosoft.com"));
var accessToken = authContext.AcquireTokenAsync("https://graph.windows.net", clientId, credentials).Result.AccessToken;
I am not a tenant admin and in AAD and I cannot add specific Applications as an owner for app authentication. This was working in full .net is there a workaround for this in .net standard? As I cannot use app authentication in this scenario.
I am trying to convert and webjob to an Azure function.
Upvotes: 3
Views: 1077
Reputation: 24529
is there a workaround for this in .net standard?
Yes, we could use the rest API to get the token directly.
Post https://login.windows.net/<tenant-id>/oauth2/token
Content-Type: application/x-www-form-urlencoded
grant_type=password
&resource={resource}
&username={username}
&password={password}
&client_id={client-id}
The following is the demo code to get access token
var tenantId = "xxx.onmicrosoft.com";
var userName = "[email protected]";
var password = "xxxxxx";
var clientId = "xxxxxxx";
using (HttpClient client = new HttpClient())
{
var tokenEndpoint = $"https://login.windows.net/{tenantId}/oauth2/token";
var accept = "application/json";
client.DefaultRequestHeaders.Add("Accept", accept);
string postBody = $"resource=https://graph.windows.net/&client_id={clientId}&grant_type=password&username={userName}&password={password}";
using (HttpResponseMessage response = await client.PostAsync(tokenEndpoint, new StringContent(postBody, Encoding.UTF8, "application/x-www-form-urlencoded")))
{
if (response.IsSuccessStatusCode)
{
var jsonresult = JObject.Parse(await response.Content.ReadAsStringAsync());
var token = (string)jsonresult["access_token"];
}
}
}
Note: Azure AD native application is requried.
Upvotes: 2